commit b4a8a70e54b7c67c737d75a648ff4e75888bace4 Author: Penguinehis <54519344+Penguinehis@users.noreply.github.com> Date: Tue Sep 29 10:05:43 2026 -0300 Upload test 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce7c7fb --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/shell2.exe +/BOT_PLAN.md +/SECURITY_REVIEW.md +/DragonCoreSSH-NewWEB.zip +/dist/ +/.tmp-bhttp-harness.exe +/Dockerfile.build +/tunnel_pipe_test.go +/docker-build.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..2470b6e --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# DragonCoreSSH CLI + +DragonCoreSSH server with a terminal administration menu and HTTP API. Based on the supplied DragonCoreSSH-NewWEB source. The supplied SSHPlus archive informed the menu organization; its code and licensing mechanism are not included. The browser panel and static assets have been removed. SSH, Xray, DNSTT, BHTTP, BTUN, HCR, UDPGW, PostgreSQL accounting, and bot/API service code remain in the Go server. + +## Install on a fresh Linux/systemd host + +Extract this archive, then run `sudo bash install.sh` from the extracted `DragonCoreSSH-CLI` directory. The installer sets up the Go server, PostgreSQL, Xray, service, and the `menu` command. If `/usr/local/bin/menu` already exists, it is saved as `menu.backup.` before the DragonCoreSSH command is installed. It generates all credentials. It needs a compatible Linux distribution and access to its system packages, the Go toolchain download, and Xray release download. Run it only on a fresh server: like the original installer it generates new database and configuration credentials. + +Run `menu` from a root shell, or `sudo menu` otherwise. The `dragoncore` command remains an alias. Other commands: `sudo menu status`, `sudo menu users`, `sudo menu logs`, `sudo menu api-password show`, `sudo menu api-password change`. The change command generates a new API password, restarts the service, verifies it, and restores the old one if verification fails. It never prompts for a password. Creating/resetting SSH users generates credentials and prints them once. + +The menu detects the terminal width. On a phone it uses a compact status header and wraps menu labels and account details; on a wider terminal it uses the fuller layout. If an SSH app reports the wrong width, run `menu --mobile` to force 40 columns, or set `DRAGONCORE_COLUMNS=36` to choose another width. For editing advanced JSON from a phone SSH client, install `nano` or set `$EDITOR` to your preferred terminal editor. + +## Migrate an existing DragonCoreSSH-NewWEB installation + +Back up `/opt/sshpanel`, its PostgreSQL database, and `/etc/systemd/system/sshpanel.service` first. Extract this release on the server and run `sudo bash update.sh` from its directory. The updater builds the CLI version, preserves `.env`, `config.json`, Xray configuration, SSH keys, accounts, and database, then restarts the service. It reads this local release only; it does not fetch the NewWEB branch. The previous binary is saved as `/opt/sshpanel/sshpanel.bak`. The old `admin/` directory is no longer served. The existing `ADMIN_HTTP_ADDR` setting is preserved; set it to `127.0.0.1:9090` and restart if remote API access is unnecessary. + +## API + +The API defaults to `http://127.0.0.1:9090` on new installations. Administrative endpoints accept `Authorization: Bearer `; use the `api-password show` command as root to view the value. Existing session-based API clients still work, including managed-server integrations. The `/check` and payment webhook endpoints remain part of the API. If exposing the API remotely for integrations, use TLS and appropriate access controls. There is no browser UI; `/` returns 404. + +Example: `curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:9090/api/users` (set `TOKEN` privately; avoid putting credentials in shell history). + +## Menu areas + +- The main menu shows live VPS OS, CPU, RAM, disk, uptime, clock, network speed, SSH online/expired/total, Xray online, and service status. The CLI falls back to local VPS metrics when the API is down. +- SSH users: list/live usage, create, create a 24-hour test account, renew/edit, change limits and quotas, generate a new SSH password, report usage/speed, reset traffic, delete expired or individual users. +- Xray: inbounds, clients, create UUID, edit/delete clients, reset traffic, status, edit JSON, start/stop/restart, and a guided shared-port setup. +- Connection modes: show SSH/TLS listeners and configured DNSTT/BHTTP/HCR/BTUN/UDPGW/Xray ports, live protocol statistics and logs, TLS certificates and issuance, DNSTT public key and key regeneration, and edit protocol settings. +- VPS and traffic: detailed network interface rates and byte totals, SSH/Xray account activity, daily/monthly traffic, system logs, build status. +- Configuration: banner, guided SSH listener ports and default limits, full server JSON, Xray JSON, bot settings display, managed servers display. The service validates settings through its API and applies server settings live. +- Reseller management remains in the Telegram bot; the CLI has no reseller menu. +- API password: view and rotate. +- Service status, logs, and restart. + +Full configuration remains available through the server API. Use the JSON editor option for settings not covered by guided prompts. This uses the editor in `$EDITOR`, or `nano` if unset. The CLI never requests a login or password. Root access to `.env` is its local authentication boundary. + +## Native Xray on the same SSH/TLS ports + +In **Xray → Share SSH/TLS ports (WS/XHTTP)**, select an existing VLESS/VMess inbound or enter a new tag. Choose WebSocket or XHTTP, then enter a distinct URL path. Leaving the path blank generates `/c1`, `/c2`, and so on. New inbounds receive a generated UUID. The menu applies and starts/restarts the native emulator. Existing inbound clients are preserved, but switching an inbound's transport requires updating their client configurations. + +Shared inbounds use `dragoncoreSharedPort: true` in the native Xray JSON. The path is required, must be more specific than `/`, and cannot overlap another shared path. The server rejects shared raw TCP and inbound TLS settings because the DragonCoreSSH public listener terminates TLS itself. Configure the client with **TLS security on the panel's TLS port** (for example 443), or no TLS on a public SSH/HTTP port (for example 80), and use the path printed by the menu. TLS XHTTP can negotiate HTTP/2; WebSocket uses HTTP/1.1. The same inbound is available on each configured public listener without a separate Xray socket. External Xray mode does not support this option. Ports owned by other processes, including a separate system sshd, cannot be shared through this router. + +## Build and checks + +Requires Go 1.25.4 and the dependencies in `go.mod`: `go build -o sshpanel .` and `go test ./...`. The CLI needs Python 3 with only the standard library. Run `python3 -m py_compile dragoncore_cli.py` and `bash -n install.sh update.sh` for syntax checks. diff --git a/auth.go b/auth.go new file mode 100644 index 0000000..279e731 --- /dev/null +++ b/auth.go @@ -0,0 +1,921 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "log" + "net" + "net/http" + "os" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/crypto/bcrypt" +) + +const ( + RoleSuperAdmin = "superadmin" + RoleReseller = "reseller" + sessionTTL = 12 * time.Hour + adminBcryptCost = 12 +) + +var adminUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) + +// ---------- AdminUser ---------- + +type AdminUser struct { + ID int + Username string + PasswordHash string + Role string + MaxUsers int + ExpiresAt *time.Time + IsActive bool + CreatedAt time.Time +} + +// ---------- Session store (in-memory) ---------- + +type AdminSession struct { + Token string + UserID int + Username string + Role string + ExpiresAt time.Time +} + +type sessionStoreT struct { + mu sync.RWMutex + m map[string]*AdminSession +} + +var sessions = &sessionStoreT{m: make(map[string]*AdminSession)} + +func (s *sessionStoreT) Create(userID int, username, role string) (*AdminSession, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return nil, fmt.Errorf("generate session token: %w", err) + } + tok := hex.EncodeToString(b) + sess := &AdminSession{ + Token: tok, + UserID: userID, + Username: username, + Role: role, + ExpiresAt: time.Now().Add(sessionTTL), + } + s.mu.Lock() + s.m[tok] = sess + s.mu.Unlock() + return sess, nil +} + +func (s *sessionStoreT) Get(token string) *AdminSession { + if token == "" { + return nil + } + s.mu.RLock() + sess := s.m[token] + s.mu.RUnlock() + if sess == nil || time.Now().After(sess.ExpiresAt) { + return nil + } + return sess +} + +func (s *sessionStoreT) Delete(token string) { + s.mu.Lock() + delete(s.m, token) + s.mu.Unlock() +} + +func (s *sessionStoreT) DeleteUser(userID int) { + s.mu.Lock() + defer s.mu.Unlock() + for token, sess := range s.m { + if sess.UserID == userID { + delete(s.m, token) + } + } +} + +func (s *sessionStoreT) cleanup() { + s.mu.Lock() + defer s.mu.Unlock() + now := time.Now() + for tok, sess := range s.m { + if now.After(sess.ExpiresAt) { + delete(s.m, tok) + } + } +} + +// ---------- In-memory AdminUser cache ---------- + +type adminUserMgrT struct { + mu sync.RWMutex + m map[string]*AdminUser +} + +var adminUsers = &adminUserMgrT{m: make(map[string]*AdminUser)} + +func (m *adminUserMgrT) set(u *AdminUser) { + m.mu.Lock() + m.m[u.Username] = u + m.mu.Unlock() +} + +func (m *adminUserMgrT) get(username string) (*AdminUser, bool) { + m.mu.RLock() + u, ok := m.m[username] + m.mu.RUnlock() + return u, ok +} + +func (m *adminUserMgrT) delete(username string) { + m.mu.Lock() + delete(m.m, username) + m.mu.Unlock() +} + +func (m *adminUserMgrT) list() []*AdminUser { + m.mu.RLock() + defer m.mu.RUnlock() + out := make([]*AdminUser, 0, len(m.m)) + for _, u := range m.m { + cp := *u + out = append(out, &cp) + } + return out +} + +func (m *adminUserMgrT) replaceAll(users []*AdminUser) { + m.mu.Lock() + m.m = make(map[string]*AdminUser, len(users)) + for _, u := range users { + cp := *u + m.m[u.Username] = &cp + } + m.mu.Unlock() +} + +// ---------- Context helpers ---------- + +type ctxKeyAdmin struct{} + +func withSession(ctx context.Context, s *AdminSession) context.Context { + return context.WithValue(ctx, ctxKeyAdmin{}, s) +} + +func sessionFromCtx(ctx context.Context) *AdminSession { + s, _ := ctx.Value(ctxKeyAdmin{}).(*AdminSession) + return s +} + +// ---------- Middleware ---------- + +// sessionMiddleware accepts the local CLI/API token or a reseller session. +// The bearer token is intentionally loaded on process start; rotating it in +// .env requires a service restart, which also revokes previous sessions. +func sessionMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") { + provided := strings.TrimPrefix(h, "Bearer ") + secret := os.Getenv("ADMIN_TOKEN") + if len(secret) >= 32 && len(provided) == len(secret) && + subtle.ConstantTimeCompare([]byte(provided), []byte(secret)) == 1 { + next.ServeHTTP(w, r.WithContext(withSession(r.Context(), &AdminSession{ + Username: "admin", Role: RoleSuperAdmin, + }))) + return + } + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + token := r.Header.Get("X-Session-Token") + s := sessions.Get(token) + if s == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + // Re-check the account on every request. This immediately revokes sessions + // after an account is suspended, expired, deleted, or has its role changed. + u, ok := adminUsers.get(s.Username) + if !ok || u.ID != s.UserID || !u.IsActive || u.Role != s.Role || + (u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt)) { + sessions.Delete(token) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r.WithContext(withSession(r.Context(), s))) + }) +} + +// superAdminOnly wraps a handler to require role == superadmin. +// Must be used AFTER sessionMiddleware (session must be in context). +func superAdminOnly(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := sessionFromCtx(r.Context()) + if s == nil || s.Role != RoleSuperAdmin { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + next.ServeHTTP(w, r) + }) +} + +// saSession chains sessionMiddleware + superAdminOnly. +func saSession(next http.Handler) http.Handler { + return sessionMiddleware(superAdminOnly(next)) +} + +// ---------- Password hashing ---------- + +func legacyAdminPasswordHash(pw string) string { + h := sha256.Sum256([]byte(pw)) + return hex.EncodeToString(h[:]) +} + +func hashAdminPassword(pw string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(pw), adminBcryptCost) + if err != nil { + return "", fmt.Errorf("hash admin password: %w", err) + } + return string(hash), nil +} + +// verifyAdminPassword accepts bcrypt and the legacy unsalted SHA-256 format. +// Legacy hashes are upgraded immediately after a successful login. +func verifyAdminPassword(storedHash, password string) (valid bool, needsUpgrade bool) { + if strings.HasPrefix(storedHash, "$2a$") || strings.HasPrefix(storedHash, "$2b$") || strings.HasPrefix(storedHash, "$2y$") { + if bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password)) != nil { + return false, false + } + cost, err := bcrypt.Cost([]byte(storedHash)) + return true, err != nil || cost < adminBcryptCost + } + if len(storedHash) != sha256.Size*2 { + return false, false + } + expected := legacyAdminPasswordHash(password) + return subtle.ConstantTimeCompare([]byte(storedHash), []byte(expected)) == 1, true +} + +func validateAdminPassword(password string) error { + if len(password) < 10 { + return fmt.Errorf("password must contain at least 10 characters") + } + if len(password) > 1024 { + return fmt.Errorf("password is too long") + } + return nil +} + +func validateAdminUsername(username string) error { + if !adminUsernamePattern.MatchString(username) { + return fmt.Errorf("username must be 1-64 characters using letters, numbers, dot, underscore, or hyphen") + } + return nil +} + +// ---------- Login throttling ---------- + +type loginAttempt struct { + Failures int + FirstSeen time.Time + BlockedTo time.Time +} + +type loginThrottleT struct { + mu sync.Mutex + attempts map[string]loginAttempt +} + +var loginThrottle = &loginThrottleT{attempts: make(map[string]loginAttempt)} + +func loginAttemptKey(r *http.Request, username string) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + return host + "\x00" + strings.ToLower(username) +} + +func (l *loginThrottleT) retryAfter(key string, now time.Time) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + a, ok := l.attempts[key] + if !ok { + return 0 + } + if !a.BlockedTo.IsZero() && now.Before(a.BlockedTo) { + return time.Until(a.BlockedTo) + } + if now.Sub(a.FirstSeen) > 15*time.Minute { + delete(l.attempts, key) + } + return 0 +} + +func (l *loginThrottleT) fail(key string, now time.Time) { + l.mu.Lock() + defer l.mu.Unlock() + a := l.attempts[key] + if a.FirstSeen.IsZero() || now.Sub(a.FirstSeen) > 15*time.Minute { + a = loginAttempt{FirstSeen: now} + } + a.Failures++ + if a.Failures >= 5 { + a.BlockedTo = now.Add(15 * time.Minute) + } + l.attempts[key] = a +} + +func (l *loginThrottleT) success(key string) { + l.mu.Lock() + delete(l.attempts, key) + l.mu.Unlock() +} + +// ---------- DB methods on Store ---------- + +func (s *Store) EnsureAdminUsersSchema(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS admin_users ( + id SERIAL PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'reseller', + max_users INT NOT NULL DEFAULT 30, + expires_at TIMESTAMPTZ, + is_active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT ''`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("EnsureAdminUsersSchema: %w", err) + } + } + return nil +} + +func (s *Store) GetAdminUserByUsername(ctx context.Context, username string) (*AdminUser, error) { + u := &AdminUser{} + var expiresAt sql.NullTime + err := s.db.QueryRowContext(ctx, + `SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at + FROM admin_users WHERE username = $1`, username, + ).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, &u.MaxUsers, + &expiresAt, &u.IsActive, &u.CreatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + if expiresAt.Valid { + u.ExpiresAt = &expiresAt.Time + } + return u, nil +} + +func (s *Store) ListAdminUsers(ctx context.Context) ([]*AdminUser, error) { + rows, err := s.db.QueryContext(ctx, + `SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at + FROM admin_users ORDER BY role, username`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*AdminUser + for rows.Next() { + u := &AdminUser{} + var expiresAt sql.NullTime + if err := rows.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, + &u.MaxUsers, &expiresAt, &u.IsActive, &u.CreatedAt); err != nil { + return nil, err + } + if expiresAt.Valid { + u.ExpiresAt = &expiresAt.Time + } + out = append(out, u) + } + return out, rows.Err() +} + +func (s *Store) UpsertAdminUser(ctx context.Context, u *AdminUser) error { + var expiresAt interface{} + if u.ExpiresAt != nil { + expiresAt = *u.ExpiresAt + } + if u.ID == 0 { + return s.db.QueryRowContext(ctx, + `INSERT INTO admin_users (username, password_hash, role, max_users, expires_at, is_active) + VALUES ($1,$2,$3,$4,$5,$6) RETURNING id`, + u.Username, u.PasswordHash, u.Role, u.MaxUsers, expiresAt, u.IsActive, + ).Scan(&u.ID) + } + _, err := s.db.ExecContext(ctx, + `UPDATE admin_users SET password_hash=$2, role=$3, max_users=$4, + expires_at=$5, is_active=$6 WHERE id=$1`, + u.ID, u.PasswordHash, u.Role, u.MaxUsers, expiresAt, u.IsActive) + return err +} + +func (s *Store) UpdateAdminPasswordHash(ctx context.Context, id int, passwordHash string) error { + _, err := s.db.ExecContext(ctx, `UPDATE admin_users SET password_hash=$2 WHERE id=$1`, id, passwordHash) + return err +} + +func (s *Store) DeleteAdminUser(ctx context.Context, username string) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM admin_users WHERE username=$1`, username) + return err +} + +func (s *Store) SetAdminUserActive(ctx context.Context, username string, active bool) error { + _, err := s.db.ExecContext(ctx, `UPDATE admin_users SET is_active=$1 WHERE username=$2`, active, username) + return err +} + +func (s *Store) ListExpiredResellers(ctx context.Context) ([]*AdminUser, error) { + rows, err := s.db.QueryContext(ctx, + `SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at + FROM admin_users + WHERE role=$1 AND is_active=TRUE AND expires_at IS NOT NULL AND expires_at < NOW()`, + RoleReseller) + if err != nil { + return nil, err + } + defer rows.Close() + return scanAdminUsers(rows) +} + +func (s *Store) ListInactiveButRenewedResellers(ctx context.Context) ([]*AdminUser, error) { + rows, err := s.db.QueryContext(ctx, + `SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at + FROM admin_users + WHERE role=$1 AND is_active=FALSE AND (expires_at IS NULL OR expires_at > NOW())`, + RoleReseller) + if err != nil { + return nil, err + } + defer rows.Close() + return scanAdminUsers(rows) +} + +func scanAdminUsers(rows *sql.Rows) ([]*AdminUser, error) { + var out []*AdminUser + for rows.Next() { + u := &AdminUser{} + var expiresAt sql.NullTime + if err := rows.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, + &u.MaxUsers, &expiresAt, &u.IsActive, &u.CreatedAt); err != nil { + return nil, err + } + if expiresAt.Valid { + u.ExpiresAt = &expiresAt.Time + } + out = append(out, u) + } + return out, rows.Err() +} + +// BootstrapSuperAdmin creates a default "admin" superadmin if none exists. +// Returns the generated password, or "" if a superadmin already existed. +func (s *Store) BootstrapSuperAdmin(ctx context.Context) (string, error) { + var count int + if err := s.db.QueryRowContext(ctx, + `SELECT COUNT(*) FROM admin_users WHERE role=$1`, RoleSuperAdmin, + ).Scan(&count); err != nil { + return "", err + } + if count > 0 { + return "", nil + } + b := make([]byte, 10) + if _, err := rand.Read(b); err != nil { + return "", fmt.Errorf("generate bootstrap password: %w", err) + } + pw := hex.EncodeToString(b) + passwordHash, err := hashAdminPassword(pw) + if err != nil { + return "", err + } + u := &AdminUser{ + Username: "admin", + PasswordHash: passwordHash, + Role: RoleSuperAdmin, + MaxUsers: 0, + IsActive: true, + } + if err := s.UpsertAdminUser(ctx, u); err != nil { + return "", err + } + return pw, nil +} + +// loadAdminUsersIntoCache reloads all admin_users rows into the in-memory cache. +func loadAdminUsersIntoCache(ctx context.Context, store *Store) error { + users, err := store.ListAdminUsers(ctx) + if err != nil { + return err + } + adminUsers.replaceAll(users) + return nil +} + +// ---------- Owner check (called from SSH auth callbacks) ---------- + +// ownerIsActive returns nil if an SSH user's reseller owner is active, or an error if suspended/expired. +func ownerIsActive(ownerUsername string) error { + if ownerUsername == "" { + return nil + } + u, ok := adminUsers.get(ownerUsername) + if !ok { + return fmt.Errorf("reseller account not found") + } + if !u.IsActive { + return fmt.Errorf("reseller account suspended") + } + if u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt) { + return fmt.Errorf("reseller account expired") + } + return nil +} + +// disconnectOwnerUsers forcibly closes all active SSH connections for users owned by owner. +func disconnectOwnerUsers(ownerUsername string) { + for _, u := range userMgr.List() { + if u.Cfg.OwnerUsername == ownerUsername { + userMgr.DisconnectUser(u.Cfg.Username) + } + } +} + +// countOwnedUsers counts SSH users in memory that belong to owner. +func countOwnedUsers(ownerUsername string) int { + n := 0 + for _, u := range userMgr.List() { + if u.Cfg.OwnerUsername == ownerUsername { + n++ + } + } + return n +} + +// ---------- Reseller expiry background checker ---------- + +func startResellerExpiryChecker(store *Store) { + if store == nil { + return + } + go func() { + ticker := time.NewTicker(60 * time.Second) + defer ticker.Stop() + for range ticker.C { + ctx := context.Background() + + // Expire active resellers past their deadline + expired, err := store.ListExpiredResellers(ctx) + if err != nil { + log.Printf("reseller expiry check: %v", err) + } + for _, u := range expired { + log.Printf("reseller %s expired — suspending", u.Username) + if err := store.SetAdminUserActive(ctx, u.Username, false); err != nil { + log.Printf("reseller expiry: %v", err) + continue + } + u.IsActive = false + adminUsers.set(u) + disconnectOwnerUsers(u.Username) + suspendOwnerXrayClients(ctx, store, u.Username) + } + + // Reactivate resellers that have been renewed (inactive but expiry now in future/nil) + renewed, err := store.ListInactiveButRenewedResellers(ctx) + if err != nil { + log.Printf("reseller renewal check: %v", err) + } + for _, u := range renewed { + log.Printf("reseller %s renewed — reactivating", u.Username) + if err := store.SetAdminUserActive(ctx, u.Username, true); err != nil { + log.Printf("reseller renewal: %v", err) + continue + } + u.IsActive = true + adminUsers.set(u) + restoreOwnerXrayClients(ctx, store, u.Username) + } + + sessions.cleanup() + } + }() +} + +// ---------- HTTP handlers ---------- + +func handleLogin(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + r.Body = http.MaxBytesReader(w, r.Body, 16*1024) + var req struct { + Username string `json:"username"` + Password string `json:"password"` + } + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + req.Username = strings.TrimSpace(req.Username) + if req.Username == "" || req.Password == "" { + http.Error(w, "username and password required", http.StatusBadRequest) + return + } + key := loginAttemptKey(r, req.Username) + now := time.Now() + if retry := loginThrottle.retryAfter(key, now); retry > 0 { + w.Header().Set("Retry-After", strconv.Itoa(max(1, int(retry.Seconds())))) + http.Error(w, "too many login attempts", http.StatusTooManyRequests) + return + } + + u, err := store.GetAdminUserByUsername(r.Context(), req.Username) + if err != nil { + log.Printf("login db: %v", err) + http.Error(w, "server error", http.StatusInternalServerError) + return + } + valid := false + needsUpgrade := false + if u != nil { + valid, needsUpgrade = verifyAdminPassword(u.PasswordHash, req.Password) + } else { + // Keep roughly the same CPU cost for unknown users to reduce account probing. + _, _ = hashAdminPassword(req.Password) + } + if !valid { + loginThrottle.fail(key, now) + http.Error(w, "invalid credentials", http.StatusUnauthorized) + return + } + if !u.IsActive { + http.Error(w, "account suspended", http.StatusForbidden) + return + } + if u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt) { + http.Error(w, "account expired", http.StatusForbidden) + return + } + + if needsUpgrade { + if upgradedHash, hashErr := hashAdminPassword(req.Password); hashErr == nil { + if updateErr := store.UpdateAdminPasswordHash(r.Context(), u.ID, upgradedHash); updateErr != nil { + log.Printf("upgrade admin password hash for %s: %v", u.Username, updateErr) + } else { + u.PasswordHash = upgradedHash + adminUsers.set(u) + } + } + } + loginThrottle.success(key) + sess, err := sessions.Create(u.ID, u.Username, u.Role) + if err != nil { + log.Printf("create admin session: %v", err) + http.Error(w, "server error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "token": sess.Token, + "username": u.Username, + "role": u.Role, + }) + } +} + +func handleLogout(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + sessions.Delete(r.Header.Get("X-Session-Token")) + w.WriteHeader(http.StatusOK) +} + +func handleMe(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + s := sessionFromCtx(r.Context()) + resp := map[string]interface{}{ + "username": s.Username, + "role": s.Role, + } + if s.Role == RoleReseller { + if u, ok := adminUsers.get(s.Username); ok { + resp["max_users"] = u.MaxUsers + resp["used_users"] = countOwnedQuota(r.Context(), statsStore, s.Username) + resp["used_ssh_users"] = countOwnedUsers(s.Username) + resp["used_xray_users"] = countOwnedXrayClients(r.Context(), statsStore, s.Username) + resp["expires_at"] = u.ExpiresAt + resp["is_active"] = u.IsActive + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + +// ---------- Reseller management (superadmin only) ---------- + +type ResellerDTO struct { + ID int `json:"id"` + Username string `json:"username"` + Role string `json:"role"` + MaxUsers int `json:"max_users"` + UsedUsers int `json:"used_users"` + UsedSSH int `json:"used_ssh_users"` + UsedXray int `json:"used_xray_users"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + IsActive bool `json:"is_active"` + CreatedAt time.Time `json:"created_at"` +} + +func handleListResellers(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + users, err := store.ListAdminUsers(r.Context()) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + out := make([]ResellerDTO, 0, len(users)) + for _, u := range users { + out = append(out, ResellerDTO{ + ID: u.ID, + Username: u.Username, + Role: u.Role, + MaxUsers: u.MaxUsers, + UsedUsers: countOwnedQuota(r.Context(), store, u.Username), + UsedSSH: countOwnedUsers(u.Username), + UsedXray: countOwnedXrayClients(r.Context(), store, u.Username), + ExpiresAt: u.ExpiresAt, + IsActive: u.IsActive, + CreatedAt: u.CreatedAt, + }) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(out) + } +} + +type ResellerPayload struct { + Username string `json:"username"` + Password string `json:"password,omitempty"` + MaxUsers int `json:"max_users"` + ExpiresAt string `json:"expires_at"` + IsActive bool `json:"is_active"` +} + +func handleCreateReseller(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var p ResellerPayload + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + p.Username = strings.TrimSpace(p.Username) + if err := validateAdminUsername(p.Username); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if p.MaxUsers < 0 || p.MaxUsers > 1000000 { + http.Error(w, "max_users must be between 0 and 1000000", http.StatusBadRequest) + return + } + + ctx := r.Context() + existing, err := store.GetAdminUserByUsername(ctx, p.Username) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + + var u *AdminUser + if existing != nil { + u = existing + } else { + if p.Password == "" { + http.Error(w, "password required for new account", http.StatusBadRequest) + return + } + u = &AdminUser{Username: p.Username, Role: RoleReseller} + } + + if p.Password != "" { + if err := validateAdminPassword(p.Password); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + passwordHash, err := hashAdminPassword(p.Password) + if err != nil { + http.Error(w, "failed to hash password", http.StatusInternalServerError) + return + } + u.PasswordHash = passwordHash + } + u.MaxUsers = p.MaxUsers + u.IsActive = p.IsActive + u.ExpiresAt = nil + if p.ExpiresAt != "" { + t, err := time.Parse(time.RFC3339, p.ExpiresAt) + if err != nil { + http.Error(w, "invalid expires_at (RFC3339 required)", http.StatusBadRequest) + return + } + u.ExpiresAt = &t + } + + if err := store.UpsertAdminUser(ctx, u); err != nil { + log.Printf("upsert reseller: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + adminUsers.set(u) + if p.Password != "" && existing != nil { + sessions.DeleteUser(u.ID) + } + + if u.Role == RoleReseller { + if !u.IsActive || (u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt)) { + disconnectOwnerUsers(u.Username) + suspendOwnerXrayClients(ctx, store, u.Username) + } else { + restoreOwnerXrayClients(ctx, store, u.Username) + } + } + + w.WriteHeader(http.StatusCreated) + } +} + +func handleDeleteReseller(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + username := strings.TrimSpace(r.URL.Query().Get("username")) + if err := validateAdminUsername(username); err != nil { + http.Error(w, "invalid username", http.StatusBadRequest) + return + } + ctx := r.Context() + u, _ := store.GetAdminUserByUsername(ctx, username) + if u != nil && u.Role == RoleSuperAdmin { + http.Error(w, "superadmin accounts cannot be deleted from the reseller endpoint", http.StatusForbidden) + return + } + if err := store.DeleteAdminUser(ctx, username); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + disconnectOwnerUsers(username) + removeOwnerXrayClients(ctx, store, username) + adminUsers.delete(username) + if u != nil { + sessions.DeleteUser(u.ID) + } + w.WriteHeader(http.StatusNoContent) + } +} diff --git a/bandwidth_rate.go b/bandwidth_rate.go new file mode 100644 index 0000000..2fbb8f7 --- /dev/null +++ b/bandwidth_rate.go @@ -0,0 +1,231 @@ +package main + +// Live per-account bandwidth. The panel already keeps cumulative uploaded and +// downloaded byte counters for every SSH user and Xray client; this file turns +// those counters into a current speed so the UI can show "↑ 12 Mbps ↓ 40 Mbps" +// for the whole account instead of only lifetime totals. Speeds are always the +// sum of every connection the account has open, because the counters they are +// derived from are per account, not per connection. + +import ( + "math" + "strings" + "sync" + "sync/atomic" + "time" +) + +// bandwidthRate is a smoothed instantaneous speed in bytes per second. +type bandwidthRate struct { + UpBytesPerSec float64 + DownBytesPerSec float64 +} + +func (r bandwidthRate) isZero() bool { + return r.UpBytesPerSec == 0 && r.DownBytesPerSec == 0 +} + +type bandwidthSample struct { + up int64 + down int64 + at time.Time + rate bandwidthRate +} + +// bandwidthSampler converts monotonically increasing byte counters into a +// speed. Deltas smaller than minSampleInterval are ignored so a double sample +// cannot divide by an almost-zero interval, and a counter that moves backwards +// (traffic reset, account recreated) re-baselines instead of reporting a +// nonsensical negative or huge rate. +type bandwidthSampler struct { + mu sync.Mutex + samples map[string]bandwidthSample + + // tau is the exponential smoothing time constant. Larger values give a + // calmer number; zero disables smoothing. + tau time.Duration + // staleAfter makes Rate report zero for accounts that stopped being + // sampled (idle Xray clients dropped by the stats poller, for example), + // instead of freezing the last speed on screen forever. + staleAfter time.Duration +} + +const minBandwidthSampleInterval = 250 * time.Millisecond + +func newBandwidthSampler(tau, staleAfter time.Duration) *bandwidthSampler { + return &bandwidthSampler{ + samples: make(map[string]bandwidthSample), + tau: tau, + staleAfter: staleAfter, + } +} + +// Observe records the current cumulative counters for key. The first +// observation only establishes a baseline; the rate stays zero until a second +// one arrives. +func (s *bandwidthSampler) Observe(key string, up, down int64, now time.Time) { + if s == nil { + return + } + key = strings.TrimSpace(key) + if key == "" { + return + } + if up < 0 { + up = 0 + } + if down < 0 { + down = 0 + } + s.mu.Lock() + defer s.mu.Unlock() + prev, ok := s.samples[key] + if !ok { + s.samples[key] = bandwidthSample{up: up, down: down, at: now} + return + } + // Counters went backwards: the account's traffic was reset or the entry was + // recycled. Start over from this value. + if up < prev.up || down < prev.down { + s.samples[key] = bandwidthSample{up: up, down: down, at: now} + return + } + dt := now.Sub(prev.at) + if dt < minBandwidthSampleInterval { + return + } + seconds := dt.Seconds() + instant := bandwidthRate{ + UpBytesPerSec: float64(up-prev.up) / seconds, + DownBytesPerSec: float64(down-prev.down) / seconds, + } + next := instant + if s.tau > 0 && !prev.rate.isZero() { + // alpha derived from the real interval so an irregular sampling + // cadence still converges on the true average. + alpha := 1 - math.Exp(-seconds/s.tau.Seconds()) + if alpha > 1 { + alpha = 1 + } + next = bandwidthRate{ + UpBytesPerSec: prev.rate.UpBytesPerSec + alpha*(instant.UpBytesPerSec-prev.rate.UpBytesPerSec), + DownBytesPerSec: prev.rate.DownBytesPerSec + alpha*(instant.DownBytesPerSec-prev.rate.DownBytesPerSec), + } + } + if next.UpBytesPerSec < 0 { + next.UpBytesPerSec = 0 + } + if next.DownBytesPerSec < 0 { + next.DownBytesPerSec = 0 + } + s.samples[key] = bandwidthSample{up: up, down: down, at: now, rate: next} +} + +// Rate returns the last known speed for key. Stale entries report zero. +func (s *bandwidthSampler) Rate(key string) (bandwidthRate, bool) { + if s == nil { + return bandwidthRate{}, false + } + key = strings.TrimSpace(key) + if key == "" { + return bandwidthRate{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + return s.rateLocked(key) +} + +// RateForKeys returns the first known speed among keys. Xray clients are +// tracked under their UUID in native mode and under their email in external +// mode, so callers pass every identifier the client may be stored under. +func (s *bandwidthSampler) RateForKeys(keys ...string) (bandwidthRate, bool) { + if s == nil { + return bandwidthRate{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + for _, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + if rate, ok := s.rateLocked(key); ok { + return rate, true + } + } + return bandwidthRate{}, false +} + +func (s *bandwidthSampler) rateLocked(key string) (bandwidthRate, bool) { + sample, ok := s.samples[key] + if !ok { + return bandwidthRate{}, false + } + if s.staleAfter > 0 && !sample.at.IsZero() && time.Since(sample.at) > s.staleAfter { + return bandwidthRate{}, true + } + return sample.rate, true +} + +// Retain drops every tracked key that is not in keep, so the map cannot grow +// forever as accounts are deleted or recreated. +func (s *bandwidthSampler) Retain(keep map[string]struct{}) { + if s == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + for key := range s.samples { + if _, ok := keep[key]; !ok { + delete(s.samples, key) + } + } +} + +// ---- SSH accounts ---- + +const sshBandwidthSampleInterval = 2 * time.Second + +var sshBandwidth = newBandwidthSampler(5*time.Second, 20*time.Second) + +func startSSHUserRateSampler() { + go func() { + ticker := time.NewTicker(sshBandwidthSampleInterval) + defer ticker.Stop() + for range ticker.C { + sampleSSHUserRates(time.Now()) + } + }() +} + +func sampleSSHUserRates(now time.Time) { + if userMgr == nil { + return + } + states := userMgr.List() + active := make(map[string]struct{}, len(states)) + for _, u := range states { + if u == nil { + continue + } + u.mu.Lock() + username := strings.TrimSpace(u.Cfg.Username) + u.mu.Unlock() + if username == "" { + continue + } + sshBandwidth.Observe( + username, + atomic.LoadInt64(&u.TotalUplinkBytes), + atomic.LoadInt64(&u.TotalDownlinkBytes), + now, + ) + active[username] = struct{}{} + } + sshBandwidth.Retain(active) +} + +func sshUserRate(username string) bandwidthRate { + rate, _ := sshBandwidth.Rate(username) + return rate +} diff --git a/bandwidth_rate_test.go b/bandwidth_rate_test.go new file mode 100644 index 0000000..ae5950d --- /dev/null +++ b/bandwidth_rate_test.go @@ -0,0 +1,121 @@ +package main + +import ( + "testing" + "time" +) + +func TestBandwidthSamplerFirstObservationIsBaselineOnly(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) + now := time.Now() + s.Observe("bob", 10_000, 20_000, now) + rate, ok := s.Rate("bob") + if !ok { + t.Fatal("expected the account to be tracked after the first observation") + } + if !rate.isZero() { + t.Fatalf("first observation must not report a speed, got %+v", rate) + } +} + +func TestBandwidthSamplerComputesBytesPerSecond(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) // no smoothing: exact delta/dt + now := time.Now() + s.Observe("bob", 0, 0, now) + // 2 MB up and 10 MB down over 2 seconds. + s.Observe("bob", 2<<20, 10<<20, now.Add(2*time.Second)) + rate, _ := s.Rate("bob") + if wantUp := float64(1 << 20); rate.UpBytesPerSec != wantUp { + t.Fatalf("up = %v, want %v", rate.UpBytesPerSec, wantUp) + } + if wantDown := float64(5 << 20); rate.DownBytesPerSec != wantDown { + t.Fatalf("down = %v, want %v", rate.DownBytesPerSec, wantDown) + } +} + +func TestBandwidthSamplerIgnoresSamplesTakenTooCloseTogether(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) + now := time.Now() + s.Observe("bob", 0, 0, now) + s.Observe("bob", 5<<20, 5<<20, now.Add(10*time.Millisecond)) + rate, _ := s.Rate("bob") + if !rate.isZero() { + t.Fatalf("a 10ms interval must not produce a speed, got %+v", rate) + } +} + +func TestBandwidthSamplerRebaselinesAfterTrafficReset(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) + now := time.Now() + s.Observe("bob", 0, 0, now) + s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second)) + // Panel reset the account's traffic: counters go back to zero. + s.Observe("bob", 0, 0, now.Add(4*time.Second)) + rate, _ := s.Rate("bob") + if !rate.isZero() { + t.Fatalf("counters moving backwards must reset the speed, got %+v", rate) + } + s.Observe("bob", 2<<20, 0, now.Add(6*time.Second)) + rate, _ = s.Rate("bob") + if wantUp := float64(1 << 20); rate.UpBytesPerSec != wantUp { + t.Fatalf("up after reset = %v, want %v", rate.UpBytesPerSec, wantUp) + } +} + +func TestBandwidthSamplerReportsZeroWhenIdle(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) + now := time.Now() + s.Observe("bob", 0, 0, now) + s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second)) + s.Observe("bob", 4<<20, 4<<20, now.Add(4*time.Second)) + rate, _ := s.Rate("bob") + if !rate.isZero() { + t.Fatalf("unchanged counters must report an idle account, got %+v", rate) + } +} + +func TestBandwidthSamplerDropsStaleSpeeds(t *testing.T) { + s := newBandwidthSampler(0, time.Second) + now := time.Now().Add(-time.Hour) + s.Observe("bob", 0, 0, now) + s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second)) + rate, ok := s.Rate("bob") + if !ok { + t.Fatal("expected the account to still be tracked") + } + if !rate.isZero() { + t.Fatalf("an hour-old sample must not still report a speed, got %+v", rate) + } +} + +func TestBandwidthSamplerSmoothsWithTimeConstant(t *testing.T) { + s := newBandwidthSampler(5*time.Second, time.Minute) + now := time.Now() + s.Observe("bob", 0, 0, now) + // First real sample has no previous rate to blend with, so it lands exactly. + s.Observe("bob", 2<<20, 0, now.Add(2*time.Second)) + first, _ := s.Rate("bob") + if first.UpBytesPerSec != float64(1<<20) { + t.Fatalf("first speed = %v, want %v", first.UpBytesPerSec, float64(1<<20)) + } + // Traffic stops: the smoothed value has to fall without jumping to zero. + s.Observe("bob", 2<<20, 0, now.Add(4*time.Second)) + second, _ := s.Rate("bob") + if second.UpBytesPerSec <= 0 || second.UpBytesPerSec >= first.UpBytesPerSec { + t.Fatalf("smoothed speed = %v, want a value between 0 and %v", second.UpBytesPerSec, first.UpBytesPerSec) + } +} + +func TestBandwidthSamplerRateForKeysAndRetain(t *testing.T) { + s := newBandwidthSampler(0, time.Minute) + now := time.Now() + s.Observe("uuid-1", 0, 0, now) + s.Observe("uuid-1", 1<<20, 0, now.Add(1*time.Second)) + if _, ok := s.RateForKeys("", "unknown@example", "uuid-1"); !ok { + t.Fatal("RateForKeys must find the client under any of its identifiers") + } + s.Retain(map[string]struct{}{"uuid-2": {}}) + if _, ok := s.Rate("uuid-1"); ok { + t.Fatal("Retain must drop accounts that no longer exist") + } +} diff --git a/bhttp_btun_integration_test.go b/bhttp_btun_integration_test.go new file mode 100644 index 0000000..aa20864 --- /dev/null +++ b/bhttp_btun_integration_test.go @@ -0,0 +1,1578 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/binary" + "io" + "log" + "net" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "shell2/internal/bhttp" + "shell2/internal/btun" + "shell2/internal/hcr" +) + +// ---------- Test scaffolding ---------- + +// withPanelUsers installs a temporary user table and SSH server config so the +// tunnel transports can be exercised against the built-in SSH server without a +// database or a real listener. +func withPanelUsers(t *testing.T, users ...*UserState) { + t.Helper() + + table := make(map[string]*UserState, len(users)) + for _, u := range users { + if u.conns == nil { + u.conns = make(map[*ssh.ServerConn]struct{}) + } + table[u.Cfg.Username] = u + } + + previousUsers := userMgr.users + userMgr.mu.Lock() + userMgr.users = table + userMgr.mu.Unlock() + + previousCfg := getSSHConfig() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generate host key: %v", err) + } + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + t.Fatalf("host key signer: %v", err) + } + sshConfig := &ssh.ServerConfig{PasswordCallback: passwordCallback} + sshConfig.AddHostKey(signer) + setSSHConfig(sshConfig) + + t.Cleanup(func() { + userMgr.mu.Lock() + userMgr.users = previousUsers + userMgr.mu.Unlock() + setSSHConfig(previousCfg) + }) +} + +// testLogger routes transport logs into the test output instead of stderr. +func testLogger(t *testing.T) *log.Logger { + t.Helper() + return log.New(testWriter{t: t}, "", 0) +} + +type testWriter struct{ t *testing.T } + +func (w testWriter) Write(p []byte) (int, error) { + w.t.Logf("%s", strings.TrimRight(string(p), "\n")) + return len(p), nil +} + +// loopbackTUN stands in for a real TUN device so the BTUN server can be +// exercised on any platform. Packets written to it are simply discarded; the +// tests here cover the handshake and accounting, not IP routing. +type loopbackTUN struct { + packets chan []byte + closed chan struct{} + once sync.Once +} + +func newLoopbackTUN() *loopbackTUN { + return &loopbackTUN{packets: make(chan []byte, 8), closed: make(chan struct{})} +} + +func (d *loopbackTUN) Read(buffer []byte) (int, error) { + select { + case packet := <-d.packets: + return copy(buffer, packet), nil + case <-d.closed: + return 0, io.EOF + } +} + +func (d *loopbackTUN) Write(buffer []byte) (int, error) { + select { + case <-d.closed: + return 0, io.ErrClosedPipe + default: + return len(buffer), nil + } +} + +func (d *loopbackTUN) Close() error { + d.once.Do(func() { close(d.closed) }) + return nil +} + +func (d *loopbackTUN) Name() string { return "tuntest0" } + +// ---------- The built-in SSH server is the only tunnel target ---------- + +// The whole point of embedding these transports is that a tunnelled session is +// served by this process's own SSH server. If dialInternalSSH ever started +// dialing a TCP address instead, tunnel logins would silently depend on the +// host's sshd, and panel accounts/limits would stop applying. +func TestDialInternalSSHIsServedInProcess(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + conn, err := dialInternalSSH("bhttp") + if err != nil { + t.Fatalf("dialInternalSSH: %v", err) + } + defer conn.Close() + + if network := conn.RemoteAddr().Network(); network != "bhttp" { + t.Fatalf("remote network = %q, want the transport label", network) + } + if _, ok := conn.(*net.TCPConn); ok { + t.Fatal("tunnel target is a TCP socket; it must stay in-process") + } + + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + banner := make([]byte, 8) + if _, err := io.ReadFull(conn, banner); err != nil { + t.Fatalf("read SSH identification: %v", err) + } + if got := string(banner); got != "SSH-2.0-" { + t.Fatalf("identification = %q, want the built-in SSH server greeting", got) + } +} + +func TestDialInternalSSHFailsBeforeTheSSHServerIsReady(t *testing.T) { + previous := getSSHConfig() + setSSHConfig(nil) + t.Cleanup(func() { setSSHConfig(previous) }) + + if _, err := dialInternalSSH("bhttp"); err == nil { + t.Fatal("expected an error while the SSH server is unavailable") + } +} + +// ---------- BHTTP end to end ---------- + +// bhttpTestClient speaks the raw BHTTP wire format against a listening server. +type bhttpTestClient struct { + t *testing.T + conn net.Conn + sid bhttp.SessionID +} + +func (c *bhttpTestClient) send(mode byte, sequence uint64, clear []byte) { + c.t.Helper() + payload := bhttp.Crypt(clear, c.sid, mode, sequence, false) + frame := make([]byte, bhttp.HeaderSize+len(payload)) + frame[0] = mode + copy(frame[1:17], c.sid[:]) + binary.BigEndian.PutUint64(frame[17:25], sequence) + binary.BigEndian.PutUint32(frame[25:29], uint32(len(payload))) + copy(frame[bhttp.HeaderSize:], payload) + if _, err := c.conn.Write(frame); err != nil { + c.t.Fatalf("write mode %d: %v", mode, err) + } +} + +// readStatus reads one status frame and returns its status byte and body. +func (c *bhttpTestClient) readStatus() (byte, []byte) { + c.t.Helper() + var header [5]byte + if _, err := io.ReadFull(c.conn, header[:]); err != nil { + c.t.Fatalf("read status header: %v", err) + } + body := make([]byte, binary.BigEndian.Uint32(header[1:5])) + if _, err := io.ReadFull(c.conn, body); err != nil { + c.t.Fatalf("read status body: %v", err) + } + return header[0], body +} + +// readDownload reads one download frame and returns the decrypted payload. +func (c *bhttpTestClient) readDownload(mode byte, sequence uint64) []byte { + c.t.Helper() + status, body := c.readStatus() + if status != bhttp.StatusData { + c.t.Fatalf("download status = %d (%q), want StatusData", status, body) + } + if len(body) < 4 { + c.t.Fatalf("download body is %d bytes, want at least 4", len(body)) + } + return bhttp.Crypt(body[4:], c.sid, mode, sequence, true) +} + +// A BHTTP client that opens a session and asks for downstream bytes must get +// the built-in SSH server's identification string, proving the whole path +// (wire framing -> session -> in-process SSH handler) is connected. +func TestBHTTPSessionReachesBuiltInSSHServer(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := bhttp.NewServer(bhttp.Config{ + TargetAddress: bhttpTargetLabel, + DialTarget: dialInternalSSH, + Logger: testLogger(t), + }) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + _ = listener.Close() + server.Close() + }) + + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + client := &bhttpTestClient{t: t, conn: conn} + copy(client.sid[:], "bhttp-e2e-sid-01") + + // Mode 1 with sequence 0 and no payload is the session open. + client.send(bhttp.ModeUpload, 0, nil) + if status, body := client.readStatus(); status != bhttp.StatusOK { + t.Fatalf("open status = %d (%q), want StatusOK", status, body) + } + + // Mode 2 pulls the first downstream chunk, which is the SSH banner. + client.send(bhttp.ModeDownload, 0, nil) + payload := client.readDownload(bhttp.ModeDownload, 0) + if !strings.HasPrefix(string(payload), "SSH-2.0-") { + t.Fatalf("first downstream chunk = %q, want the built-in SSH identification", payload) + } +} + +// The session cap has to refuse new session IDs rather than grow without +// bound, otherwise a client spraying random SIDs allocates a session (and an +// SSH handler) per frame. +func TestBHTTPSessionCapRefusesNewSessions(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := bhttp.NewServer(bhttp.Config{ + TargetAddress: bhttpTargetLabel, + DialTarget: dialInternalSSH, + MaxSessions: 1, + Logger: testLogger(t), + }) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + _ = listener.Close() + server.Close() + }) + + open := func(sid string) (byte, []byte) { + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + client := &bhttpTestClient{t: t, conn: conn} + copy(client.sid[:], sid) + client.send(bhttp.ModeUpload, 0, nil) + return client.readStatus() + } + + // A bhttp.SessionID is exactly 16 bytes, so these labels must differ within + // the first 16 characters or they would name the same session. + if status, body := open("bhttp-cap-sid-1"); status != bhttp.StatusOK { + t.Fatalf("first session status = %d (%q), want StatusOK", status, body) + } + if status, _ := open("bhttp-cap-sid-2"); status == bhttp.StatusOK { + t.Fatal("second session was accepted past the cap of 1") + } + if stats := server.Stats(); stats.SessionsRejected == 0 { + t.Fatal("rejected session was not counted") + } +} + +func TestNormalizeBHTTPListenListDeduplicates(t *testing.T) { + got := normalizeBHTTPListenList([]string{" 0.0.0.0:8880 ", "", "0.0.0.0:8880", "[::]:8881"}) + want := []string{"0.0.0.0:8880", "[::]:8881"} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("got %v, want %v", got, want) + } + } +} + +// ---------- BTUN authentication is panel-only ---------- + +func TestBTUNAuthenticatorUsesPanelAccountsOnly(t *testing.T) { + past := time.Now().Add(-time.Hour) + future := time.Now().Add(time.Hour) + + valid := &UserState{Cfg: UserConfig{Username: "valid", Password: "pass"}} + expired := &UserState{Cfg: UserConfig{Username: "expired", Password: "pass"}, ExpiresAt: &past} + active := &UserState{Cfg: UserConfig{Username: "active", Password: "pass"}, ExpiresAt: &future} + quota := &UserState{Cfg: UserConfig{ + Username: "quota", Password: "pass", + DataQuotaBytes: 1024, QuotaAction: quotaActionBlock, + }} + atomic.StoreInt64("a.totalBytes, 4096) + + withPanelUsers(t, valid, expired, active, quota) + + auth := btunPanelAuthenticator{} + if auth.Name() != "panel" { + t.Fatalf("authenticator name = %q, want \"panel\"", auth.Name()) + } + + tests := []struct { + name string + username string + password string + wantErr bool + }{ + {name: "panel password accepted", username: "valid", password: "pass"}, + {name: "unexpired account accepted", username: "active", password: "pass"}, + {name: "wrong password rejected", username: "valid", password: "nope", wantErr: true}, + {name: "unknown account rejected", username: "ghost", password: "pass", wantErr: true}, + {name: "expired account rejected", username: "expired", password: "pass", wantErr: true}, + {name: "account over data quota rejected", username: "quota", password: "pass", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := auth.Authenticate(tt.username, tt.password) + if (err != nil) != tt.wantErr { + t.Fatalf("Authenticate(%q) error = %v, wantErr %v", tt.username, err, tt.wantErr) + } + }) + } +} + +// A system account that is not a panel account must never be able to log in +// over BTUN, even with pam_auth_enabled turned on: pam_auth_enabled is an SSH +// setting and BTUN has no PAM path at all. +func TestBTUNAuthenticatorIgnoresSystemLoginSetting(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "panelonly", Password: "pass"}}) + + setPAMAuthEnabled(true) + t.Cleanup(func() { setPAMAuthEnabled(false) }) + + auth := btunPanelAuthenticator{} + if err := auth.Authenticate("root", "toor"); err == nil { + t.Fatal("a non-panel account was accepted over BTUN") + } +} + +// ---------- BTUN accounting shares the account's allowances with SSH ---------- + +type fakeCloser struct{ closed atomic.Bool } + +func (c *fakeCloser) Close() error { + c.closed.Store(true) + return nil +} + +func TestBTUNSessionsShareMaxConnectionsWithSSH(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "limited", Password: "pass", MaxConnections: 2}} + withPanelUsers(t, user) + + accountant := btunPanelAccountant{} + first, err := accountant.Admit("limited", "203.0.113.5:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("first session refused: %v", err) + } + second, err := accountant.Admit("limited", "203.0.113.5:1001", &fakeCloser{}) + if err != nil { + t.Fatalf("second session refused: %v", err) + } + if _, err := accountant.Admit("limited", "203.0.113.5:1002", &fakeCloser{}); err == nil { + t.Fatal("third session was admitted past max_connections = 2") + } + + user.mu.Lock() + counted := user.btunConns + reported := user.ActiveConns + user.mu.Unlock() + if counted != 2 || reported != 2 { + t.Fatalf("btunConns = %d, ActiveConns = %d, want 2 and 2", counted, reported) + } + + // Closing a session must free the slot again. + second.Close() + if _, err := accountant.Admit("limited", "203.0.113.5:1003", &fakeCloser{}); err != nil { + t.Fatalf("session refused after a slot was freed: %v", err) + } + first.Close() +} + +func TestBTUNDisconnectUserClosesItsSessions(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "kickme", Password: "pass"}} + other := &UserState{Cfg: UserConfig{Username: "keepme", Password: "pass"}} + withPanelUsers(t, user, other) + + accountant := btunPanelAccountant{} + victimCloser := &fakeCloser{} + bystanderCloser := &fakeCloser{} + victim, err := accountant.Admit("kickme", "203.0.113.9:1000", victimCloser) + if err != nil { + t.Fatalf("admit: %v", err) + } + bystander, err := accountant.Admit("keepme", "203.0.113.9:1001", bystanderCloser) + if err != nil { + t.Fatalf("admit: %v", err) + } + t.Cleanup(func() { + victim.Close() + bystander.Close() + }) + + if closed := btunDisconnectUser("kickme"); closed != 1 { + t.Fatalf("btunDisconnectUser closed %d sessions, want 1", closed) + } + if !victimCloser.closed.Load() { + t.Fatal("the user's own BTUN session was not closed") + } + if bystanderCloser.closed.Load() { + t.Fatal("another user's BTUN session was closed") + } +} + +// Forwarding whole IP packets cannot honour a partial quota allowance, so the +// account's remaining bytes must end the session instead of letting a +// truncated packet through. +func TestBTUNLedgerStopsAtTheDataQuota(t *testing.T) { + user := &UserState{Cfg: UserConfig{ + Username: "capped", Password: "pass", + DataQuotaBytes: 4096, QuotaAction: quotaActionBlock, + }} + withPanelUsers(t, user) + + ledger, err := (btunPanelAccountant{}).Admit("capped", "203.0.113.20:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("admit: %v", err) + } + defer ledger.Close() + + if err := ledger.Uplink(t.Context(), 1024); err != nil { + t.Fatalf("first packet within quota was refused: %v", err) + } + if err := ledger.Downlink(t.Context(), 1024); err != nil { + t.Fatalf("second packet within quota was refused: %v", err) + } + if got := atomic.LoadInt64(&user.TotalUplinkBytes); got != 1024 { + t.Fatalf("uplink bytes = %d, want 1024", got) + } + if got := atomic.LoadInt64(&user.TotalDownlinkBytes); got != 1024 { + t.Fatalf("downlink bytes = %d, want 1024", got) + } + + // This packet crosses the 4096-byte quota, so it must be refused whole. + if err := ledger.Uplink(t.Context(), 4096); err == nil { + t.Fatal("a packet past the data quota was allowed") + } + if got := atomic.LoadInt64(&user.TotalUplinkBytes); got != 1024 { + t.Fatalf("refused packet was still counted: uplink bytes = %d, want 1024", got) + } +} + +func TestBTUNLedgerPacesAtTheAccountBandwidthLimit(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "slow", Password: "pass", LimitMbpsUp: 1, LimitMbpsDown: 1}} + withPanelUsers(t, user) + + ledger, err := (btunPanelAccountant{}).Admit("slow", "203.0.113.30:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("admit: %v", err) + } + defer ledger.Close() + + // A 1 Mbps limiter refills at 131072 bytes/s and starts with a full bucket, + // so the first 128 KiB go through immediately and the next 64 KiB must wait + // roughly half a second rather than being refused outright. + const packet = 64 * 1024 + for i := 0; i < 2; i++ { + if err := ledger.Uplink(t.Context(), packet); err != nil { + t.Fatalf("packet %d within the initial burst was refused: %v", i+1, err) + } + } + start := time.Now() + if err := ledger.Uplink(t.Context(), packet); err != nil { + t.Fatalf("packet past the initial burst was refused: %v", err) + } + if elapsed := time.Since(start); elapsed < 100*time.Millisecond { + t.Fatalf("packet past the burst took %s; the bandwidth limit was not applied", elapsed) + } +} + +// ---------- BTUN configuration ---------- + +func TestBTUNGatewayForSubnet(t *testing.T) { + tests := []struct { + subnet string + want string + wantErr bool + }{ + {subnet: "10.77.0.0/16", want: "10.77.0.1/16"}, + {subnet: "10.8.0.0/24", want: "10.8.0.1/24"}, + {subnet: "192.168.20.0/30", want: "192.168.20.1/30"}, + {subnet: "10.9.0.5/24", want: "10.9.0.1/24"}, + {subnet: "10.10.0.0/31", wantErr: true}, + {subnet: "fd00::/64", wantErr: true}, + {subnet: "not-a-subnet", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.subnet, func(t *testing.T) { + got, err := btunGatewayForSubnet(tt.subnet) + if (err != nil) != tt.wantErr { + t.Fatalf("btunGatewayForSubnet(%q) error = %v, wantErr %v", tt.subnet, err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Fatalf("btunGatewayForSubnet(%q) = %q, want %q", tt.subnet, got, tt.want) + } + }) + } +} + +func TestNormalizeBTUNConfigFillsDefaults(t *testing.T) { + cfg := &BTUNConfig{TCPListen: " 0.0.0.0:7300 "} + normalizeBTUNConfig(cfg) + + if cfg.TCPListen != "0.0.0.0:7300" { + t.Fatalf("tcp_listen = %q", cfg.TCPListen) + } + if cfg.TUNName != defaultBTUNName { + t.Fatalf("tun_name = %q, want %q", cfg.TUNName, defaultBTUNName) + } + if cfg.Subnet != defaultBTUNSubnet { + t.Fatalf("subnet = %q, want %q", cfg.Subnet, defaultBTUNSubnet) + } + if cfg.Gateway != "10.77.0.1/16" { + t.Fatalf("gateway = %q, want 10.77.0.1/16", cfg.Gateway) + } + if cfg.MTU != defaultBTUNMTU { + t.Fatalf("mtu = %d, want %d", cfg.MTU, defaultBTUNMTU) + } +} + +func TestNormalizeBTUNConfigClampsPacketSize(t *testing.T) { + cfg := &BTUNConfig{UDPListen: "0.0.0.0:7300", MaxPacketSize: 64 * 1024 * 1024} + normalizeBTUNConfig(cfg) + if cfg.MaxPacketSize != btunMaxPacketCeiling { + t.Fatalf("max_packet_size = %d, want %d", cfg.MaxPacketSize, btunMaxPacketCeiling) + } +} + +// A BTUN server started without a listener would silently do nothing, so the +// misconfiguration has to surface as a start error the panel can show. +func TestStartBTUNInstanceRequiresAListener(t *testing.T) { + err := startBTUNInstance(&BTUNConfig{}) + if err == nil { + t.Fatal("expected an error when neither listener is configured") + } + if !strings.Contains(err.Error(), "tcp_listen") { + t.Fatalf("error = %v, want it to name the missing setting", err) + } +} + +func TestNormalizeAutoRestartFields(t *testing.T) { + tests := []struct { + name string + interval string + grace string + wantInterval string + wantGrace string + }{ + {name: "kept as configured", interval: "6h", grace: "2s", wantInterval: "6h", wantGrace: "2s"}, + {name: "interval below the minimum disables", interval: "30s", grace: "", wantInterval: "", wantGrace: ""}, + {name: "invalid interval disables", interval: "soon", grace: "", wantInterval: "", wantGrace: ""}, + {name: "off keeps its sentinel", interval: "off", grace: "", wantInterval: "off", wantGrace: ""}, + {name: "invalid grace falls back", interval: "2h", grace: "later", wantInterval: "2h", wantGrace: ""}, + {name: "long grace is clamped", interval: "2h", grace: "5m", wantInterval: "2h", wantGrace: "1m"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + interval, grace := tt.interval, tt.grace + normalizeAutoRestartFields(&interval, &grace, "TEST", func(string, ...interface{}) {}) + if interval != tt.wantInterval || grace != tt.wantGrace { + t.Fatalf("got (%q, %q), want (%q, %q)", interval, grace, tt.wantInterval, tt.wantGrace) + } + }) + } +} + +func TestNormalizeDurationFieldClamps(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + {name: "empty stays empty", input: "", want: ""}, + {name: "in range is kept", input: "45s", want: "45s"}, + {name: "below minimum clamps up", input: "1s", want: "10s"}, + {name: "above maximum clamps down", input: "5h", want: "1h0m0s"}, + {name: "invalid clears", input: "nope", want: ""}, + {name: "zero clears", input: "0s", want: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.input + normalizeDurationField(&got, "test", 10*time.Second, time.Hour, func(string, ...interface{}) {}) + if got != tt.want { + t.Fatalf("normalizeDurationField(%q) = %q, want %q", tt.input, got, tt.want) + } + }) + } +} + +// ---------- BTUN wire behaviour against the panel authenticator ---------- + +// The BTUN handshake must reject a bad panel credential and accept a good one, +// which is what proves the panel authenticator is actually wired into the +// protocol server rather than being dead code. +func TestBTUNHandshakeAuthenticatesAgainstThePanel(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + + device := newLoopbackTUN() + server, err := btun.NewServer(btun.Config{ + Subnet: "10.77.0.0/24", + Authenticator: btunPanelAuthenticator{}, + Accountant: btunPanelAccountant{}, + Logger: testLogger(t), + }, device) + if err != nil { + t.Fatalf("new BTUN server: %v", err) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + go func() { _ = server.ServeTCP(listener) }() + t.Cleanup(func() { + _ = listener.Close() + _ = server.Close() + server.Wait() + }) + + authenticate := func(credential string) btun.Packet { + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + if _, err := conn.Write(btun.ClientHello); err != nil { + t.Fatalf("write client hello: %v", err) + } + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(conn, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte(credential)}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + packet, err := btun.ReadPacket(conn, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + return packet + } + + accepted := authenticate("vpn:letmein") + if accepted.Type != btun.PacketAuthResponse || len(accepted.Payload) == 0 || accepted.Payload[0] != 1 { + t.Fatalf("valid panel credential was rejected: %#v", accepted) + } + + refused := authenticate("vpn:wrong") + if refused.Type != btun.PacketAuthResponse || len(refused.Payload) == 0 || refused.Payload[0] != 0 { + t.Fatalf("invalid panel credential was accepted: %#v", refused) + } + + unknown := authenticate("nosuchuser:letmein") + if unknown.Type != btun.PacketAuthResponse || len(unknown.Payload) == 0 || unknown.Payload[0] != 0 { + t.Fatalf("unknown account was accepted: %#v", unknown) + } +} + +// ---------- BHTTP sharing the proxy and TLS ports ---------- + +// withSharedBHTTP starts a BHTTP instance that owns no port of its own and +// only serves connections handed over from the panel's listeners. +func withSharedBHTTP(t *testing.T) { + t.Helper() + if err := startBHTTPInstance(&BHTTPConfig{SharedPorts: true}); err != nil { + t.Fatalf("start shared BHTTP: %v", err) + } + t.Cleanup(stopBHTTP) + if !bhttpShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// serveProxyPort starts a listener that behaves like a public proxy port. +func serveProxyPort(t *testing.T) net.Addr { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go handleProxyConn(conn, getSSHConfig()) + } + }() + return listener.Addr() +} + +// bhttpProbeFrame builds the BHP1 capability probe a client opens with. +func bhttpProbeFrame(sid bhttp.SessionID) []byte { + clear := make([]byte, 10) + copy(clear[:4], "BHP1") + clear[4] = 1 + clear[5] = bhttp.ModeUpload + payload := bhttp.Crypt(clear, sid, bhttp.ModeProbe, 0, false) + frame := make([]byte, bhttp.HeaderSize+len(payload)) + frame[0] = bhttp.ModeProbe + copy(frame[1:17], sid[:]) + binary.BigEndian.PutUint32(frame[25:29], uint32(len(payload))) + copy(frame[bhttp.HeaderSize:], payload) + return frame +} + +// A BHTTP client on a port the HTTP+SSH proxy owns must be answered by BHTTP, +// and must never receive the proxy's unsolicited "HTTP/1.1 101" line. +func TestSharedProxyPortServesBHTTPClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + var sid bhttp.SessionID + copy(sid[:], "shared-probe-s01") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + status, body := client.readStatus() + if status != bhttp.StatusOK { + t.Fatalf("probe status = %d (%q), want StatusOK — the proxy answered instead of BHTTP", status, body) + } + decoded := bhttp.Crypt(body, sid, bhttp.ModeProbe, 0, true) + if len(decoded) < 4 || string(decoded[:4]) != "BHP1" { + t.Fatalf("probe response = %q, want a BHP1 reply", decoded) + } +} + +// The same shared port must still serve the HTTP-injection SSH flow exactly as +// before: the 101, the 200, and then the built-in SSH server's banner. +func TestSharedProxyPortStillServesInjectedSSH(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + // An injection client sends its HTTP payload and SSH banner together. + if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\nSSH-2.0-TestClient\r\n")); err != nil { + t.Fatalf("write payload: %v", err) + } + + got := readUntil(t, conn, "SSH-2.0-") + if !strings.Contains(got, "HTTP/1.1 101") { + t.Fatalf("response %q is missing the 101 the injection flow expects", got) + } + if !strings.Contains(got, "HTTP/1.1 200") { + t.Fatalf("response %q is missing the 200 the injection flow expects", got) + } +} + +// A BHTTP client that hides behind an HTTP cover request on the shared port +// has to be picked up after the injection cleanup consumes that cover. +func TestSharedProxyPortServesBHTTPBehindHTTPCover(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + var sid bhttp.SessionID + copy(sid[:], "shared-cover-s01") + payload := append([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"), bhttpProbeFrame(sid)...) + if _, err := conn.Write(payload); err != nil { + t.Fatalf("write payload: %v", err) + } + + // The proxy answers the cover request itself, so skip its HTTP lines and + // then read the BHTTP status frame that follows. + reader := bufio.NewReader(conn) + skipHTTPResponses(t, reader) + status, body := readStatusFrom(t, reader) + if status != bhttp.StatusOK { + t.Fatalf("probe status = %d (%q), want StatusOK", status, body) + } + decoded := bhttp.Crypt(body, sid, bhttp.ModeProbe, 0, true) + if len(decoded) < 4 || string(decoded[:4]) != "BHP1" { + t.Fatalf("probe response = %q, want a BHP1 reply", decoded) + } +} + +// With sharing off, the shared port must behave exactly as it did before this +// feature existed: a BHTTP frame gets the proxy's HTTP handling, not BHTTP. +func TestSharedProxyPortIgnoresBHTTPWhenSharingIsOff(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + if bhttpShareEnabled() { + t.Fatal("shared-port handoff is unexpectedly active") + } + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + // The proxy greets with 101 before reading anything, which is the behaviour + // a BHTTP client cannot tolerate and why sharing is a deliberate choice. + got := readUntil(t, conn, "HTTP/1.1 101") + if !strings.Contains(got, "HTTP/1.1 101") { + t.Fatalf("response %q, want the proxy's unsolicited 101", got) + } +} + +// readUntil reads until marker appears or the deadline fires. +func readUntil(t *testing.T, conn net.Conn, marker string) string { + t.Helper() + var seen []byte + buffer := make([]byte, 256) + for { + n, err := conn.Read(buffer) + if n > 0 { + seen = append(seen, buffer[:n]...) + if strings.Contains(string(seen), marker) { + return string(seen) + } + } + if err != nil { + t.Fatalf("read (looking for %q, got %q): %v", marker, seen, err) + } + } +} + +// skipHTTPResponses consumes the proxy's HTTP status lines and their blank +// separator lines, stopping at the first byte that is not part of one. +func skipHTTPResponses(t *testing.T, reader *bufio.Reader) { + t.Helper() + for { + peeked, err := reader.Peek(5) + if err != nil { + t.Fatalf("peek HTTP response: %v", err) + } + if string(peeked) != "HTTP/" { + return + } + for { + line, err := reader.ReadString('\n') + if err != nil { + t.Fatalf("read HTTP line: %v", err) + } + if strings.TrimRight(line, "\r\n") == "" { + break + } + } + } +} + +func readStatusFrom(t *testing.T, reader *bufio.Reader) (byte, []byte) { + t.Helper() + var header [5]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + t.Fatalf("read status header: %v", err) + } + body := make([]byte, binary.BigEndian.Uint32(header[1:5])) + if _, err := io.ReadFull(reader, body); err != nil { + t.Fatalf("read status body: %v", err) + } + return header[0], body +} + +// ---------- Panel policy on the BHTTP transport path ---------- + +// dialTunnelSSHClient completes a real SSH client handshake over the same +// in-process transport BHTTP hands its sessions to. +func dialTunnelSSHClient(t *testing.T, username, password string) (*ssh.Client, error) { + t.Helper() + conn, err := dialInternalSSH("bhttp") + if err != nil { + t.Fatalf("dialInternalSSH: %v", err) + } + clientConn, chans, reqs, err := ssh.NewClientConn(conn, "bhttp", &ssh.ClientConfig{ + User: username, + Auth: []ssh.AuthMethod{ssh.Password(password)}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + _ = conn.Close() + return nil, err + } + return ssh.NewClient(clientConn, chans, reqs), nil +} + +// A BHTTP session is an SSH connection on the built-in server, so every panel +// rule the SSH path enforces has to apply to it with no BHTTP-specific code: +// the account must exist and match, and the session must be counted against +// the account like any other. +func TestBHTTPTransportAppliesPanelAccountPolicy(t *testing.T) { + user := &UserState{Cfg: UserConfig{ + Username: "tunnel", Password: "secret", + MaxConnections: 1, LimitMbpsUp: 5, LimitMbpsDown: 10, + }} + expired := time.Now().Add(-time.Hour) + stale := &UserState{Cfg: UserConfig{Username: "stale", Password: "secret"}, ExpiresAt: &expired} + withPanelUsers(t, user, stale) + + // A wrong password must be refused by the same callback SSH uses. + if client, err := dialTunnelSSHClient(t, "tunnel", "wrong"); err == nil { + _ = client.Close() + t.Fatal("a wrong password was accepted over the BHTTP transport path") + } + // So must an expired account. + if client, err := dialTunnelSSHClient(t, "stale", "secret"); err == nil { + _ = client.Close() + t.Fatal("an expired account was accepted over the BHTTP transport path") + } + + client, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err != nil { + t.Fatalf("valid account was refused: %v", err) + } + defer client.Close() + + // handleConn registers the session, which is what makes max_connections, + // the panel's active-user count and forced disconnects cover BHTTP. + deadline := time.Now().Add(5 * time.Second) + for { + user.mu.Lock() + active := len(user.conns) + user.mu.Unlock() + if active == 1 { + break + } + if time.Now().After(deadline) { + t.Fatalf("BHTTP session was not registered on the account (active = %d)", active) + } + time.Sleep(10 * time.Millisecond) + } + + // max_connections is 1, so a second session must be dropped. + second, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err == nil { + // The cap is enforced after the handshake, so the connection is closed + // rather than refused: the first use of it fails. + _, _, sessErr := second.OpenChannel("session", nil) + _ = second.Close() + if sessErr == nil { + t.Fatal("a second session was usable past max_connections = 1") + } + } +} + +// The per-account bandwidth limits and data quota are applied by the +// direct-tcpip relay, which is the only data path a BHTTP session has. This +// pins the wiring that derives them, including the global default fallback. +func TestBHTTPTransportDerivesAccountLimits(t *testing.T) { + setDefaultLimits(7, 9) + t.Cleanup(func() { setDefaultLimits(0, 0) }) + + tests := []struct { + name string + cfg UserConfig + wantUp int + wantDown int + }{ + {name: "per-account limits win", cfg: UserConfig{LimitMbpsUp: 5, LimitMbpsDown: 10}, wantUp: 5, wantDown: 10}, + {name: "zero falls back to the default", cfg: UserConfig{}, wantUp: 7, wantDown: 9}, + {name: "one side falls back", cfg: UserConfig{LimitMbpsUp: 3}, wantUp: 3, wantDown: 9}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + up, down := tt.cfg.LimitMbpsUp, tt.cfg.LimitMbpsDown + if up == 0 || down == 0 { + defUp, defDown := getDefaultLimits() + if up == 0 { + up = defUp + } + if down == 0 { + down = defDown + } + } + if up != tt.wantUp || down != tt.wantDown { + t.Fatalf("limits = (%d, %d), want (%d, %d)", up, down, tt.wantUp, tt.wantDown) + } + }) + } +} + +// ---------- BTUN sharing the proxy and TLS ports ---------- + +// withSharedBTUN starts a BTUN instance that owns no port of its own and only +// serves connections handed over from the panel's listeners. +func withSharedBTUN(t *testing.T) { + t.Helper() + device := newLoopbackTUN() + server, err := btun.NewServer(btun.Config{ + Subnet: "10.77.0.0/24", + Authenticator: btunPanelAuthenticator{}, + Accountant: btunPanelAccountant{}, + Logger: testLogger(t), + }, device) + if err != nil { + t.Fatalf("new BTUN server: %v", err) + } + btunMu.Lock() + btunServer = server + btunDevice = device + btunSharedPorts = true + btunMu.Unlock() + t.Cleanup(func() { + btunMu.Lock() + btunServer = nil + btunDevice = nil + btunSharedPorts = false + btunMu.Unlock() + _ = server.Close() + server.Wait() + }) + if !btunShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// btunAuthenticate runs the BTUN handshake over conn and returns the server's +// authentication response. +func btunAuthenticate(t *testing.T, conn net.Conn, reader *bufio.Reader, credential string) btun.Packet { + t.Helper() + if _, err := conn.Write(btun.ClientHello); err != nil { + t.Fatalf("write client hello: %v", err) + } + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(reader, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + if !bytes.Equal(hello, btun.ServerHello) { + t.Fatalf("server hello = %q, want %q", hello, btun.ServerHello) + } + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte(credential)}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + packet, err := btun.ReadPacket(reader, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + return packet +} + +// A BTUN client on a port the HTTP+SSH proxy owns must reach BTUN and +// authenticate against the panel accounts. +func TestSharedProxyPortServesBTUNClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:letmein") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("valid panel credential was rejected on the shared port: %#v", response) + } +} + +// A BTUN client hiding behind an HTTP cover request must be picked up after the +// injection cleanup consumes that cover. +func TestSharedProxyPortServesBTUNBehindHTTPCover(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + // The cover and the hello go out together, which is what the protocol + // requires: a dedicated BTUN server answers nothing until it has read the + // hello, so a client cannot wait for a reply to the cover alone. + cover := append([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"), btun.ClientHello...) + if _, err := conn.Write(cover); err != nil { + t.Fatalf("write cover: %v", err) + } + + // On a shared port the client also has to skip the panel's own 101/200 + // injection reply before the server hello. That is the cost of sharing, and + // the reason the dedicated BTUN port stays available for clients that do + // not expect it. + reader := bufio.NewReader(conn) + skipHTTPResponses(t, reader) + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(reader, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + if !bytes.Equal(hello, btun.ServerHello) { + t.Fatalf("server hello = %q, want %q", hello, btun.ServerHello) + } + + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte("vpn:letmein")}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + response, err := btun.ReadPacket(reader, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("BTUN behind HTTP cover was rejected: %#v", response) + } +} + +// A wrong panel credential must be refused on the shared port exactly as on a +// dedicated one: sharing changes routing, never authentication. +func TestSharedProxyPortBTUNStillChecksPanelCredentials(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:wrong") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 0 { + t.Fatalf("invalid credential was accepted on the shared port: %#v", response) + } +} + +// The decisive test: all three protocols on one listener at the same time, +// each answered correctly, none disturbed by the others. +func TestSharedProxyPortServesAllThreeProtocols(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBHTTP(t) + withSharedBTUN(t) + addr := serveProxyPort(t) + + t.Run("BTUN", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:letmein") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("BTUN was not served: %#v", response) + } + }) + + t.Run("BHTTP", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + var sid bhttp.SessionID + copy(sid[:], "all-three-sid-01") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + status, body := client.readStatus() + if status != bhttp.StatusOK { + t.Fatalf("BHTTP was not served: status %d (%q)", status, body) + } + }) + + t.Run("injected SSH", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n\r\nSSH-2.0-TestClient\r\n")); err != nil { + t.Fatalf("write payload: %v", err) + } + got := readUntil(t, conn, "SSH-2.0-") + if !strings.Contains(got, "HTTP/1.1 200") { + t.Fatalf("injected SSH lost its 200: %q", got) + } + }) +} + +// ---------- UDP over the tunnel transports ---------- + +// The SSH-carrying transports move TCP. UDP reaches the internet through the +// panel's built-in custom BadVPN gateway, which a client reaches by opening a +// direct-tcpip channel to it over the same tunnel. This proves that whole path: +// BHTTP transport -> built-in SSH server -> direct-tcpip -> UDPGW -> UDP peer. +func TestUDPGWIsReachableOverTheTunnelTransport(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + // A UDP peer that echoes back what it receives, standing in for a DNS or + // game server the client wants to reach. + echo, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen UDP echo: %v", err) + } + defer echo.Close() + go func() { + buffer := make([]byte, 2048) + for { + n, from, err := echo.ReadFrom(buffer) + if err != nil { + return + } + _, _ = echo.WriteTo(buffer[:n], from) + } + }() + echoAddr := echo.LocalAddr().(*net.UDPAddr) + + // The gateway itself, bound to loopback for the test. + if err := startUDPGW(&UDPGWConfig{Listen: "127.0.0.1:0"}); err != nil { + t.Fatalf("start UDPGW: %v", err) + } + t.Cleanup(stopUDPGW) + udpgwMu.Lock() + gatewayAddr := "" + if udpgwLn != nil { + gatewayAddr = udpgwLn.Addr().String() + } + udpgwMu.Unlock() + if gatewayAddr == "" { + t.Fatal("UDPGW did not bind a listener") + } + + // Connect the way a BHTTP client does, then tunnel to the gateway. + client, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err != nil { + t.Fatalf("tunnel SSH login: %v", err) + } + defer client.Close() + + gateway, err := client.Dial("tcp", gatewayAddr) + if err != nil { + t.Fatalf("direct-tcpip to the UDP gateway: %v", err) + } + defer gateway.Close() + _ = gateway.SetDeadline(time.Now().Add(15 * time.Second)) + + payload := []byte("udp-over-tunnel") + if _, err := gateway.Write(udpgwFrame(1, echoAddr, payload)); err != nil { + t.Fatalf("write udpgw frame: %v", err) + } + + connID, from, echoed := readUDPGWFrame(t, gateway) + if connID != 1 { + t.Fatalf("reply connID = %d, want 1", connID) + } + if from != uint16(echoAddr.Port) { + t.Fatalf("reply port = %d, want %d", from, echoAddr.Port) + } + if string(echoed) != string(payload) { + t.Fatalf("echoed %q, want %q", echoed, payload) + } +} + +// udpgwFrame builds one client->server frame in the panel's custom BadVPN +// framing: len(2, little endian) | connID(2) | x(1) | IPv4(4) | port(2) | data. +func udpgwFrame(connID uint16, dst *net.UDPAddr, data []byte) []byte { + body := make([]byte, 9+len(data)) + binary.BigEndian.PutUint16(body[0:2], connID) + body[2] = 0 + copy(body[3:7], dst.IP.To4()) + binary.BigEndian.PutUint16(body[7:9], uint16(dst.Port)) + copy(body[9:], data) + + out := make([]byte, 2+len(body)) + binary.LittleEndian.PutUint16(out[0:2], uint16(len(body))) + copy(out[2:], body) + return out +} + +// readUDPGWFrame reads one server->client frame and returns its connID, source +// port and payload. +func readUDPGWFrame(t *testing.T, conn net.Conn) (uint16, uint16, []byte) { + t.Helper() + var header [2]byte + if _, err := io.ReadFull(conn, header[:]); err != nil { + t.Fatalf("read udpgw length: %v", err) + } + body := make([]byte, binary.LittleEndian.Uint16(header[:])) + if _, err := io.ReadFull(conn, body); err != nil { + t.Fatalf("read udpgw body: %v", err) + } + if len(body) < 9 { + t.Fatalf("udpgw reply is %d bytes, want at least 9", len(body)) + } + return binary.BigEndian.Uint16(body[0:2]), binary.BigEndian.Uint16(body[7:9]), body[9:] +} + +// ---------- HCR sharing the proxy and TLS ports ---------- + +// withSharedHCR starts an HCR instance owning no port of its own; it only +// serves connections handed over from the panel's listeners. +func withSharedHCR(t *testing.T) { + t.Helper() + server := hcr.NewServer(&hcr.Config{ + DialTarget: func() (net.Conn, error) { return dialInternalSSH("hcr") }, + Logger: nil, + MaxSessions: 100, + }) + ctx, cancel := context.WithCancel(context.Background()) + hcrMu.Lock() + hcrServer = server + hcrCtx = ctx + hcrCancel = cancel + hcrSharedPorts = true + hcrMu.Unlock() + t.Cleanup(func() { + hcrMu.Lock() + hcrServer = nil + hcrCtx = nil + hcrCancel = nil + hcrSharedPorts = false + hcrMu.Unlock() + cancel() + server.Close() + server.Wait() + }) + if !hcrShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// hcrMaskPayload mirrors the engine's payload cipher so the test can encode +// requests and decode responses. It is the same SHA-256 keystream XOR. +func sha256Sum(b []byte) [32]byte { return sha256.Sum256(b) } + +func hcrMaskPayload(payload []byte, sid [16]byte, code uint8, seq uint64, direction uint8) { + if len(payload) == 0 { + return + } + var seed [30]byte + copy(seed[0:16], sid[:]) + seed[16] = code + binary.BigEndian.PutUint64(seed[17:25], seq) + seed[25] = direction + for offset := 0; offset < len(payload); offset += 32 { + binary.BigEndian.PutUint32(seed[26:30], uint32(offset/32)) + block := sha256Sum(seed[:]) + for i := 0; i < 32 && offset+i < len(payload); i++ { + payload[offset+i] ^= block[i] + } + } +} + +// hcrConnectFrame builds a 62-byte Connect request. +func hcrConnectFrame(sid [16]byte) []byte { + b := make([]byte, hcr.RequestHeaderSize) + b[0] = 1 // ReqConnect + b[1] = 1 // ProtoVersion + copy(b[2:18], sid[:]) + return b +} + +// hcrPollFrame builds a Poll request for up to maxChunks records at seq. +func hcrPollFrame(sid [16]byte, seq uint64, maxChunks uint16) []byte { + payload := make([]byte, 2) + binary.BigEndian.PutUint16(payload, maxChunks) + hcrMaskPayload(payload, sid, 3, seq, 0) // ReqPoll, DirRequest + b := make([]byte, hcr.RequestHeaderSize+len(payload)) + b[0] = 3 // ReqPoll + b[1] = 1 + copy(b[2:18], sid[:]) + binary.BigEndian.PutUint64(b[50:58], seq) + binary.BigEndian.PutUint32(b[58:62], uint32(len(payload))) + copy(b[hcr.RequestHeaderSize:], payload) + return b +} + +// hcrReadResponse reads a 14-byte response header plus its payload. +func hcrReadResponse(t *testing.T, r *bufio.Reader) (status byte, seq uint64, payload []byte) { + t.Helper() + var hdr [14]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + t.Fatalf("read HCR response header: %v", err) + } + status = hdr[0] + seq = binary.BigEndian.Uint64(hdr[2:10]) + n := binary.BigEndian.Uint32(hdr[10:14]) + if n > 0 { + payload = make([]byte, n) + if _, err := io.ReadFull(r, payload); err != nil { + t.Fatalf("read HCR response payload: %v", err) + } + } + return status, seq, payload +} + +// An HCR client on a port the HTTP+SSH proxy owns must reach the built-in SSH +// server: Connect succeeds, then a Poll returns the SSH banner. +func TestSharedProxyPortServesHCRClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedHCR(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + reader := bufio.NewReader(conn) + + var sid [16]byte + copy(sid[:], "hcr-shared-sid01") + + if _, err := conn.Write(hcrConnectFrame(sid)); err != nil { + t.Fatalf("write connect: %v", err) + } + status, _, _ := hcrReadResponse(t, reader) + if status != 0 { // StatusOk + t.Fatalf("connect status = %d, want StatusOk — the proxy answered instead of HCR", status) + } + + // Poll for the SSH banner the target sends first. + if _, err := conn.Write(hcrPollFrame(sid, 0, 4)); err != nil { + t.Fatalf("write poll: %v", err) + } + status, seq, payload := hcrReadResponse(t, reader) + if status != 1 { // StatusPollData + t.Fatalf("poll status = %d, want StatusPollData(1)", status) + } + hcrMaskPayload(payload, sid, 3, seq, 1) // ReqPoll, DirResponse + if len(payload) < 4 { + t.Fatalf("poll payload too short: %d bytes", len(payload)) + } + chunkLen := binary.BigEndian.Uint32(payload[:4]) + banner := payload[4 : 4+chunkLen] + if !strings.HasPrefix(string(banner), "SSH-2.0-") { + t.Fatalf("first HCR download = %q, want the built-in SSH identification", banner) + } +} + +// The decisive coexistence test: HCR, BHTTP, BTUN and injected SSH all served +// on one listener at once, each answered correctly. +func TestSharedProxyPortServesHCRAlongsideBHTTP(t *testing.T) { + withPanelUsers(t, + &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}, + &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}, + ) + withSharedHCR(t) + withSharedBHTTP(t) + withSharedBTUN(t) + addr := serveProxyPort(t) + + t.Run("HCR", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + reader := bufio.NewReader(conn) + var sid [16]byte + copy(sid[:], "coexist-hcr-sid1") + if _, err := conn.Write(hcrConnectFrame(sid)); err != nil { + t.Fatalf("write connect: %v", err) + } + if status, _, _ := hcrReadResponse(t, reader); status != 0 { + t.Fatalf("HCR was not served: connect status %d", status) + } + }) + + t.Run("BHTTP", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + var sid bhttp.SessionID + copy(sid[:], "coexist-bhttp-s1") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + if status, body := client.readStatus(); status != bhttp.StatusOK { + t.Fatalf("BHTTP was not served: status %d (%q)", status, body) + } + }) + + t.Run("BTUN", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:letmein") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("BTUN was not served: %#v", response) + } + }) +} diff --git a/bhttp_integration.go b/bhttp_integration.go new file mode 100644 index 0000000..d58b195 --- /dev/null +++ b/bhttp_integration.go @@ -0,0 +1,532 @@ +package main + +// This file embeds the BHTTP (BHP1/BHP2) transport into the panel. BHTTP is the +// obfuscated TCP transport used by the DTunnel-family clients: a client opens a +// plain TCP socket, optionally sends an HTTP request as cover, then speaks the +// 29-byte-header BHTTP framing (probe, upload, download, batch, ACK and — in +// v2 — persistent lanes with resume and cumulative ACKs). +// +// The transport does NOT talk to the system's OpenSSH daemon. Exactly like the +// DNSTT integration, every BHTTP session is handed to this process's own SSH +// server through handleConn, so panel accounts, expiry, TOTP, per-user +// bandwidth limits, data quotas and connection counters all apply unchanged. +// There is no dependency on sshd, PAM or /etc/shadow anywhere in this path. + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "strings" + "sync" + "time" + + "shell2/internal/bhttp" +) + +// BHTTPConfig defines the settings for the integrated BHTTP transport. A nil +// *BHTTPConfig in the main config disables it entirely. +type BHTTPConfig struct { + // Listen lists the TCP addresses to bind. IPv6 addresses must use bracket + // form, for example "[::]:8880". Empty uses the default 0.0.0.0:8880. + // Ports 80/8080 normally belong to the HTTP+SSH proxy listeners, so BHTTP + // defaults to a separate port instead of fighting them for the socket. + Listen []string `json:"listen"` + + // SharedPorts also accepts BHTTP on the ports the panel already owns: the + // HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080) + // and every TLS forwarder (normally 443). Those listeners read the first + // bytes of each connection and hand it here only when it is unmistakably a + // BHTTP frame, so SSH and HTTP-injection clients on the same port are + // unaffected. + // + // The one behaviour this changes for other clients: the proxy listener + // normally answers with "HTTP/1.1 101" the moment a socket opens, and with + // sharing on it waits for the client's first bytes instead (up to + // bhttpSniffTimeout). Every known client sends immediately on connect, but + // turn this off if a client of yours waits for that 101 before speaking. + SharedPorts bool `json:"shared_ports,omitempty"` + + // SessionTimeout is how long a BHTTP session may sit with no traffic before + // it is dropped and its SSH connection closed. Empty defaults to "2m". + // BHTTP v2 clients reconnect lanes into an existing session, so this value + // also bounds how long a resume stays possible. + SessionTimeout string `json:"session_timeout,omitempty"` + + // MaxV2Lanes caps the combined number of BHTTP v2 lanes a single session + // may keep attached. Zero uses the protocol default (128). + MaxV2Lanes int `json:"max_v2_lanes,omitempty"` + + // MaxSessions caps concurrently tracked BHTTP sessions. Once reached, new + // session IDs are refused while existing sessions keep working. Zero uses a + // safe default; negative disables the cap. + MaxSessions int `json:"max_sessions,omitempty"` + + // MaxConnections caps concurrently accepted client sockets across every + // BHTTP listener. Sockets past the cap are closed before any protocol work. + // Zero uses a safe default; negative disables the cap. + MaxConnections int `json:"max_connections,omitempty"` + + // DisableConsoleLog keeps BHTTP log lines out of stderr. They are still + // captured in memory and served by /api/bhttp/logs for the panel. + DisableConsoleLog bool `json:"disable_console_log,omitempty"` + + // LogConnections enables one log line per accepted socket. Leave it off on + // servers with thousands of users; connection logging can become the + // bottleneck. + LogConnections bool `json:"log_connections,omitempty"` + + // AutoRestartInterval controls a watchdog that periodically hard-restarts + // only the BHTTP listeners and drops their sessions. Empty, "0s", "off" or + // "disabled" turns it off. Minimum accepted value is 1m. + AutoRestartInterval string `json:"auto_restart_interval,omitempty"` + + // AutoRestartGrace is the delay between closing the old listeners and + // binding them again during an auto restart. Empty defaults to "2s". + AutoRestartGrace string `json:"auto_restart_grace,omitempty"` +} + +const ( + defaultBHTTPListen = "0.0.0.0:8880" + defaultBHTTPSessionTimeout = 2 * time.Minute + defaultBHTTPMaxSessions = 10000 + defaultBHTTPMaxConnections = 10000 + // bhttpTargetLabel is the "address" handed to the dialer. BHTTP never dials + // a TCP target, so this is only what shows up in logs. + bhttpTargetLabel = "bhttp" +) + +var ( + bhttpMu sync.Mutex + bhttpServer *bhttp.Server + bhttpListeners []net.Listener + bhttpAddrs []string + // bhttpSharedPorts mirrors BHTTPConfig.SharedPorts for the running + // instance, so the proxy and TLS listeners can check it without reading the + // whole config on every connection. + bhttpSharedPorts bool + + bhttpAutoMu sync.Mutex + bhttpAutoCancel context.CancelFunc + + bhttpLog = log.New(os.Stderr, "bhttp: ", log.LstdFlags|log.Lmicroseconds) + bhttpLogBuf *ringLogBuffer +) + +// ---------- Log buffer shared by the embedded transports ---------- + +// ringLogBuffer keeps the most recent log lines in memory so the admin panel +// can show them even when console logging is disabled. +type ringLogBuffer struct { + mu sync.Mutex + lines []string + maxLines int + partial string +} + +func newRingLogBuffer(maxLines int) *ringLogBuffer { + if maxLines <= 0 { + maxLines = 100 + } + return &ringLogBuffer{lines: make([]string, 0, maxLines), maxLines: maxLines} +} + +func (b *ringLogBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + text := b.partial + string(p) + b.partial = "" + for { + index := strings.IndexByte(text, '\n') + if index < 0 { + b.partial = text + break + } + line := strings.TrimRight(text[:index], "\r") + text = text[index+1:] + if line == "" { + continue + } + if len(b.lines) >= b.maxLines { + copy(b.lines, b.lines[1:]) + b.lines = b.lines[:len(b.lines)-1] + } + b.lines = append(b.lines, line) + } + return len(p), nil +} + +func (b *ringLogBuffer) GetLines() []string { + if b == nil { + return nil + } + b.mu.Lock() + defer b.mu.Unlock() + out := make([]string, len(b.lines)) + copy(out, b.lines) + return out +} + +func getBHTTPLogLines() []string { return bhttpLogBuf.GetLines() } + +// ---------- Handing a tunnelled stream to the built-in SSH server ---------- + +// transportAddr is a stable net.Addr placeholder for in-process tunnel streams, +// mirroring how the DNSTT integration labels its streams. +type transportAddr string + +func (a transportAddr) Network() string { return string(a) } +func (a transportAddr) String() string { return string(a) } + +// dialInternalSSH returns a net.Conn whose other end is being served by this +// process's own SSH server. Nothing leaves the process: no loopback socket, no +// system sshd, no PAM. label only affects log output. +// +// The pair is buffered in both directions (see tunnel_pipe.go), so neither +// side has to be reading for the other to make progress. That keeps the SSH +// server's handshake, which writes and reads in the same goroutine, from +// depending on the transport happening to be draining at that moment. +func dialInternalSSH(label string) (net.Conn, error) { + sshConf := getSSHConfig() + if sshConf == nil { + return nil, fmt.Errorf("%s: internal SSH server is not ready", label) + } + clientSide, serverSide := newTunnelConnPair(label, tunnelPipeBuffer) + go func() { + defer func() { + if r := recover(); r != nil { + log.Printf("%s: recovered panic in SSH handler: %v", label, r) + } + }() + defer serverSide.Close() + handleConn(serverSide, sshConf) + }() + return clientSide, nil +} + +// ---------- Lifecycle ---------- + +// stopBHTTP closes the BHTTP listeners, drops every session and stops the +// optional auto-restart watchdog. It is a no-op if BHTTP is not running. +func stopBHTTP() { + stopBHTTPAutoRestart() + stopBHTTPInstance() +} + +// stopBHTTPInstance closes only the listeners and sessions. The auto-restart +// watchdog uses this so it can cycle BHTTP without disabling itself. +func stopBHTTPInstance() { + bhttpMu.Lock() + listeners := bhttpListeners + server := bhttpServer + bhttpListeners = nil + bhttpAddrs = nil + bhttpServer = nil + bhttpSharedPorts = false + bhttpMu.Unlock() + + for _, listener := range listeners { + if listener != nil { + _ = listener.Close() + } + } + if server != nil { + server.Close() + } +} + +func stopBHTTPAutoRestart() { + bhttpAutoMu.Lock() + defer bhttpAutoMu.Unlock() + if bhttpAutoCancel != nil { + bhttpAutoCancel() + bhttpAutoCancel = nil + } +} + +func bhttpRunning() bool { + bhttpMu.Lock() + defer bhttpMu.Unlock() + // The server can legitimately run with no listener of its own when it only + // serves connections handed over from the shared proxy and TLS ports. + return bhttpServer != nil +} + +// bhttpListenList describes where BHTTP is reachable, for the panel. +func bhttpListenList() string { + bhttpMu.Lock() + addrs := append([]string(nil), bhttpAddrs...) + shared := bhttpSharedPorts + bhttpMu.Unlock() + if shared { + addrs = append(addrs, "shared proxy/TLS ports") + } + return strings.Join(addrs, ", ") +} + +// bhttpShareEnabled reports whether a running BHTTP server wants the shared +// proxy and TLS ports. +func bhttpShareEnabled() bool { + bhttpMu.Lock() + defer bhttpMu.Unlock() + return bhttpServer != nil && bhttpSharedPorts +} + +func bhttpEnabledInCurrentConfig() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.BHTTP != nil +} + +// startBHTTP starts the integrated BHTTP transport if cfg is non-nil. Startup +// errors are returned so the admin panel can report them, but they never crash +// the panel. +func startBHTTP(cfg *BHTTPConfig) error { + if cfg == nil { + return nil + } + stopBHTTPAutoRestart() + if err := startBHTTPInstance(cfg); err != nil { + return err + } + startBHTTPAutoRestart(cfg) + return nil +} + +func startBHTTPInstance(cfg *BHTTPConfig) error { + if cfg == nil { + return nil + } + if bhttpLogBuf == nil { + bhttpLogBuf = newRingLogBuffer(200) + } + if cfg.DisableConsoleLog { + bhttpLog.SetOutput(bhttpLogBuf) + } else { + bhttpLog.SetOutput(io.MultiWriter(bhttpLogBuf, os.Stderr)) + } + + addrs := normalizeBHTTPListenList(cfg.Listen) + cfg.Listen = addrs + if len(addrs) == 0 && !cfg.SharedPorts { + msg := errors.New("bhttp: needs either a listen address or shared_ports") + bhttpLog.Print(msg.Error()) + return msg + } + + sessionTimeout := bhttpSessionTimeout(cfg) + maxSessions := cfg.MaxSessions + if maxSessions == 0 { + maxSessions = defaultBHTTPMaxSessions + } else if maxSessions < 0 { + maxSessions = 0 // unlimited + } + maxConnections := cfg.MaxConnections + if maxConnections == 0 { + maxConnections = defaultBHTTPMaxConnections + } else if maxConnections < 0 { + maxConnections = 0 // unlimited + } + + server := bhttp.NewServer(bhttp.Config{ + TargetAddress: bhttpTargetLabel, + SessionTimeout: sessionTimeout, + MaxV2Lanes: cfg.MaxV2Lanes, + MaxSessions: maxSessions, + MaxConnections: maxConnections, + LogConnections: cfg.LogConnections, + Logger: bhttpLog, + DialTarget: dialInternalSSH, + }) + + // Release the previous instance first: rebinding the same address while the + // old socket is still open would fail with "address already in use". + stopBHTTPInstance() + + // Bind synchronously so the panel immediately knows whether BHTTP really + // started or failed on a busy port. + listeners := make([]net.Listener, 0, len(addrs)) + bound := make([]string, 0, len(addrs)) + for _, addr := range addrs { + listener, err := net.Listen("tcp", addr) + if err != nil { + for _, opened := range listeners { + _ = opened.Close() + } + server.Close() + msg := fmt.Errorf("bhttp: listen failed on %s: %w", addr, err) + bhttpLog.Print(msg.Error()) + return msg + } + listeners = append(listeners, listener) + bound = append(bound, addr) + } + + bhttpMu.Lock() + bhttpServer = server + bhttpListeners = listeners + bhttpAddrs = bound + bhttpSharedPorts = cfg.SharedPorts + bhttpMu.Unlock() + + bhttpLog.Printf("starting: listen=%q shared_ports=%v session_timeout=%s max_v2_lanes=%d max_sessions=%d max_connections=%d log_connections=%v -> built-in SSH server", + bound, cfg.SharedPorts, sessionTimeout, cfg.MaxV2Lanes, maxSessions, maxConnections, cfg.LogConnections) + + for _, listener := range listeners { + go func(current net.Listener) { + defer func() { + if r := recover(); r != nil { + bhttpLog.Printf("recovered panic in accept loop: %v", r) + } + }() + if err := server.Serve(current); err != nil && !isListenerClosed(err) { + bhttpLog.Printf("listener %s stopped: %v", current.Addr(), err) + } + }(listener) + } + return nil +} + +func startBHTTPAutoRestart(cfg *BHTTPConfig) { + interval := bhttpAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := bhttpAutoRestartGrace(cfg) + cfgCopy := *cfg + cfgCopy.Listen = append([]string(nil), cfg.Listen...) + ctx, cancel := context.WithCancel(context.Background()) + + bhttpAutoMu.Lock() + if bhttpAutoCancel != nil { + bhttpAutoCancel() + } + bhttpAutoCancel = cancel + bhttpAutoMu.Unlock() + + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + bhttpLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace) + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + bhttpLog.Print("auto restart: stopping listeners and sessions") + stopBHTTPInstance() + if !sleepOrContextDone(ctx, grace) { + return + } + for attempt := 1; ; attempt++ { + if err := startBHTTPInstance(&cfgCopy); err != nil { + bhttpLog.Printf("auto restart: start attempt %d failed: %v", attempt, err) + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + continue + } + bhttpLog.Print("auto restart: listeners rebound") + break + } + } + } + }() +} + +func bhttpSessionTimeout(cfg *BHTTPConfig) time.Duration { + if cfg == nil { + return defaultBHTTPSessionTimeout + } + raw := strings.TrimSpace(cfg.SessionTimeout) + if raw == "" { + return defaultBHTTPSessionTimeout + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + bhttpLog.Printf("invalid session_timeout %q; using default %s", raw, defaultBHTTPSessionTimeout) + return defaultBHTTPSessionTimeout + } + return d +} + +func bhttpAutoRestartInterval(cfg *BHTTPConfig) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.AutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + bhttpLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err) + return 0 + } + if d < time.Minute { + bhttpLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw) + return 0 + } + return d +} + +func bhttpAutoRestartGrace(cfg *BHTTPConfig) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace)) + if err != nil || d < 0 { + bhttpLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace) + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +// normalizeBHTTPListenList trims, de-duplicates and preserves the order of the +// configured listen addresses. +func normalizeBHTTPListenList(addrs []string) []string { + seen := make(map[string]bool, len(addrs)) + out := make([]string, 0, len(addrs)) + for _, addr := range addrs { + addr = strings.TrimSpace(addr) + if addr == "" || seen[addr] { + continue + } + seen[addr] = true + out = append(out, addr) + } + return out +} + +// ---------- Stats ---------- + +// BHTTPStatsSnapshot is what /api/bhttp returns. +type BHTTPStatsSnapshot struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Listen string `json:"listen,omitempty"` + bhttp.StatsSnapshot +} + +// GetBHTTPStatsSnapshot returns the current BHTTP counters. It is safe for +// concurrent use and always returns a copy. +func GetBHTTPStatsSnapshot() BHTTPStatsSnapshot { + snapshot := BHTTPStatsSnapshot{ + Enabled: bhttpEnabledInCurrentConfig(), + Running: bhttpRunning(), + Listen: bhttpListenList(), + } + bhttpMu.Lock() + server := bhttpServer + bhttpMu.Unlock() + if server != nil { + snapshot.StatsSnapshot = server.Stats() + } + return snapshot +} diff --git a/bot_api.go b/bot_api.go new file mode 100644 index 0000000..bd4a5f2 --- /dev/null +++ b/bot_api.go @@ -0,0 +1,583 @@ +package main + +// bot_api.go — /api/bot/* admin endpoints (superadmin). + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + "unicode" +) + +var botSettingKeys = map[string]int{ + "welcome_text": 4096, + "contact_text": 4096, + "app_text": 4096, + "app_url": 2048, +} + +func botHasControlCharacters(value string) bool { + return strings.IndexFunc(value, func(r rune) bool { + return unicode.IsControl(r) && r != '\n' && r != '\r' && r != '\t' + }) >= 0 +} + +func botHasAnyControlCharacters(value string) bool { + return strings.IndexFunc(value, unicode.IsControl) >= 0 +} + +func validateBotPlan(p *BotPlan) error { + p.Name = strings.TrimSpace(p.Name) + p.Kind = strings.ToLower(strings.TrimSpace(p.Kind)) + p.XrayProtocol = strings.ToLower(strings.TrimSpace(p.XrayProtocol)) + p.XrayInboundTag = strings.TrimSpace(p.XrayInboundTag) + p.ServerID = strings.TrimSpace(p.ServerID) + if p.Name == "" || len(p.Name) > 120 || botHasControlCharacters(p.Name) { + return fmt.Errorf("plan name must contain 1-120 safe characters") + } + if p.Kind != "ssh" && p.Kind != "xray" { + return fmt.Errorf("plan kind must be ssh or xray") + } + if p.Days < 1 || p.Days > 3650 || p.MaxConnections < 0 || p.MaxConnections > 10000 { + return fmt.Errorf("invalid plan duration or connection limit") + } + if p.LimitMbpsUp < 0 || p.LimitMbpsUp > 1000000 || p.LimitMbpsDown < 0 || p.LimitMbpsDown > 1000000 { + return fmt.Errorf("invalid bandwidth limit") + } + if p.PriceCents < 0 || p.PriceCents > 1000000000 || p.CreditCost < 0 || p.CreditCost > 1000000000 { + return fmt.Errorf("invalid plan price or credit cost") + } + if p.Kind == "xray" && p.XrayProtocol != "" && p.XrayProtocol != "vless" && p.XrayProtocol != "vmess" && p.XrayProtocol != "trojan" { + return fmt.Errorf("invalid Xray protocol") + } + if len(p.XrayInboundTag) > 128 || len(p.ServerID) > 128 { + return fmt.Errorf("inbound tag or server id is too long") + } + return nil +} + +func validateBotPackage(p *BotCreditPackage) error { + p.Name = strings.TrimSpace(p.Name) + if p.Name == "" || len(p.Name) > 120 || botHasControlCharacters(p.Name) { + return fmt.Errorf("package name must contain 1-120 safe characters") + } + if p.Credits < 1 || p.Credits > 1000000000 || p.PriceCents < 0 || p.PriceCents > 1000000000 { + return fmt.Errorf("invalid package credits or price") + } + return nil +} + +func botWriteJSON(w http.ResponseWriter, v interface{}) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} + +func botStoreReady(w http.ResponseWriter, store *Store) bool { + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return false + } + return true +} + +// ---------- Config ---------- + +type botConfigDTO struct { + Enabled bool `json:"enabled"` + MPConfirmMode string `json:"mp_confirm_mode"` + MPPollInterval string `json:"mp_poll_interval"` + PixExpirationMinutes int `json:"pix_expiration_minutes"` + TrialEnabled bool `json:"trial_enabled"` + TrialHours int `json:"trial_hours"` + TrialMaxConnections int `json:"trial_max_connections"` + TrialKind string `json:"trial_kind"` + TrialInboundTag string `json:"trial_inbound_tag"` + AdminTelegramIDs []int64 `json:"admin_telegram_ids"` + Currency string `json:"currency"` + PublicHost string `json:"public_host"` + XrayPublicHost string `json:"xray_public_host"` + HasTelegramToken bool `json:"has_telegram_token"` + HasMPAccessToken bool `json:"has_mp_access_token"` + HasMPWebhookSecret bool `json:"has_mp_webhook_secret"` + // Write-only secret fields (empty on GET; empty on POST = keep existing). + TelegramToken string `json:"telegram_token"` + MPAccessToken string `json:"mp_access_token"` + MPWebhookSecret string `json:"mp_webhook_secret"` +} + +func handleBotConfig(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + cfg, err := LoadBotConfig(ctx, store) + if err != nil { + http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError) + return + } + botWriteJSON(w, botConfigDTO{ + Enabled: cfg.Enabled, + MPConfirmMode: cfg.MPConfirmMode, + MPPollInterval: cfg.MPPollInterval, + PixExpirationMinutes: cfg.PixExpirationMinutes, + TrialEnabled: cfg.TrialEnabled, + TrialHours: cfg.TrialHours, + TrialMaxConnections: cfg.TrialMaxConnections, + TrialKind: cfg.TrialKind, + TrialInboundTag: cfg.TrialInboundTag, + AdminTelegramIDs: cfg.AdminTelegramIDs, + Currency: cfg.Currency, + PublicHost: cfg.PublicHost, + XrayPublicHost: cfg.XrayPublicHost, + HasTelegramToken: cfg.TelegramToken != "", + HasMPAccessToken: cfg.MPAccessToken != "", + HasMPWebhookSecret: cfg.MPWebhookSecret != "", + }) + case http.MethodPost: + var dto botConfigDTO + r.Body = http.MaxBytesReader(w, r.Body, 64*1024) + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&dto); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + dto.MPConfirmMode = strings.ToLower(strings.TrimSpace(dto.MPConfirmMode)) + if dto.MPConfirmMode != "polling" && dto.MPConfirmMode != "webhook" { + http.Error(w, "confirmation mode must be polling or webhook", http.StatusBadRequest) + return + } + pollInterval, err := time.ParseDuration(strings.TrimSpace(dto.MPPollInterval)) + if err != nil || pollInterval < 5*time.Second || pollInterval > 5*time.Minute { + http.Error(w, "poll interval must be between 5s and 5m", http.StatusBadRequest) + return + } + if dto.PixExpirationMinutes < 5 || dto.PixExpirationMinutes > 1440 || dto.TrialHours < 1 || dto.TrialHours > 720 || dto.TrialMaxConnections < 1 || dto.TrialMaxConnections > 1000 { + http.Error(w, "invalid PIX expiration or trial limits", http.StatusBadRequest) + return + } + dto.TrialKind = strings.ToLower(strings.TrimSpace(dto.TrialKind)) + if dto.TrialKind != "ssh" && dto.TrialKind != "xray" { + http.Error(w, "trial kind must be ssh or xray", http.StatusBadRequest) + return + } + if len(dto.AdminTelegramIDs) > 100 { + http.Error(w, "too many admin Telegram IDs", http.StatusBadRequest) + return + } + for _, id := range dto.AdminTelegramIDs { + if id <= 0 { + http.Error(w, "admin Telegram IDs must be positive", http.StatusBadRequest) + return + } + } + for _, value := range []string{dto.TelegramToken, dto.MPAccessToken, dto.MPWebhookSecret, dto.PublicHost, dto.XrayPublicHost, dto.TrialInboundTag} { + if len(value) > 2048 || botHasAnyControlCharacters(value) { + http.Error(w, "configuration contains an invalid value", http.StatusBadRequest) + return + } + } + existing, err := LoadBotConfig(ctx, store) + if err != nil { + http.Error(w, "load existing config", http.StatusInternalServerError) + return + } + effectiveTelegramToken := strings.TrimSpace(dto.TelegramToken) + if effectiveTelegramToken == "" { + effectiveTelegramToken = existing.TelegramToken + } + if dto.Enabled && effectiveTelegramToken == "" { + http.Error(w, "Telegram token is required before enabling the bot", http.StatusBadRequest) + return + } + effectiveWebhookSecret := strings.TrimSpace(dto.MPWebhookSecret) + if effectiveWebhookSecret == "" { + effectiveWebhookSecret = existing.MPWebhookSecret + } + if dto.MPConfirmMode == "webhook" && len(effectiveWebhookSecret) < 16 { + http.Error(w, "a webhook secret of at least 16 characters is required", http.StatusBadRequest) + return + } + cfg := &BotConfig{ + Enabled: dto.Enabled, + TelegramToken: strings.TrimSpace(dto.TelegramToken), + MPAccessToken: strings.TrimSpace(dto.MPAccessToken), + MPConfirmMode: dto.MPConfirmMode, + MPWebhookSecret: strings.TrimSpace(dto.MPWebhookSecret), + MPPollInterval: dto.MPPollInterval, + PixExpirationMinutes: dto.PixExpirationMinutes, + TrialEnabled: dto.TrialEnabled, + TrialHours: dto.TrialHours, + TrialMaxConnections: dto.TrialMaxConnections, + TrialKind: dto.TrialKind, + TrialInboundTag: strings.TrimSpace(dto.TrialInboundTag), + AdminTelegramIDs: dto.AdminTelegramIDs, + Currency: dto.Currency, + PublicHost: strings.TrimSpace(dto.PublicHost), + XrayPublicHost: strings.TrimSpace(dto.XrayPublicHost), + } + if err := SaveBotConfig(ctx, store, cfg); err != nil { + http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError) + return + } + reloadBotService(store) + botWriteJSON(w, map[string]bool{"ok": true}) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Plans ---------- + +func handleBotPlans(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + plans, err := store.ListPlans(ctx, false) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, plans) + case http.MethodPost: + var p BotPlan + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if p.Kind == "" { + p.Kind = "ssh" + } + if err := validateBotPlan(&p); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := store.UpsertPlan(ctx, &p); err != nil { + http.Error(w, "db error: "+err.Error(), http.StatusInternalServerError) + return + } + botWriteJSON(w, p) + case http.MethodDelete: + id, _ := strconv.Atoi(r.URL.Query().Get("id")) + if id <= 0 { + http.Error(w, "invalid id", http.StatusBadRequest) + return + } + if err := store.DeletePlan(ctx, id); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Credit packages ---------- + +func handleBotCreditPackages(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + pkgs, err := store.ListCreditPackages(ctx, false) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, pkgs) + case http.MethodPost: + var p BotCreditPackage + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if err := validateBotPackage(&p); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := store.UpsertCreditPackage(ctx, &p); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, p) + case http.MethodDelete: + id, _ := strconv.Atoi(r.URL.Query().Get("id")) + if id <= 0 { + http.Error(w, "invalid id", http.StatusBadRequest) + return + } + if err := store.DeleteCreditPackage(ctx, id); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Bot users ---------- + +func handleBotUsers(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + users, err := store.ListBotUsers(ctx) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, users) + case http.MethodPost: + var req struct { + TelegramID int64 `json:"telegram_id"` + Action string `json:"action"` + Role string `json:"role"` + LinkedAdminUsername string `json:"linked_admin_username"` + Credits int `json:"credits"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.TelegramID == 0 { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + switch req.Action { + case "set_role": + if req.Role == "" { + req.Role = "customer" + } + req.Role = strings.ToLower(strings.TrimSpace(req.Role)) + if req.Role != "customer" && req.Role != "reseller" && req.Role != "blocked" { + http.Error(w, "role must be customer, reseller, or blocked", http.StatusBadRequest) + return + } + req.LinkedAdminUsername = strings.TrimSpace(req.LinkedAdminUsername) + if req.Role == "reseller" { + linked, err := store.GetAdminUserByUsername(ctx, req.LinkedAdminUsername) + if err != nil || linked == nil || linked.Role != RoleReseller { + http.Error(w, "linked reseller account not found", http.StatusBadRequest) + return + } + } else { + req.LinkedAdminUsername = "" + } + if err := store.SetBotUserRole(ctx, req.TelegramID, req.Role, req.LinkedAdminUsername); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + case "block": + if err := store.SetBotUserRole(ctx, req.TelegramID, "blocked", ""); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + case "unblock": + if err := store.SetBotUserRole(ctx, req.TelegramID, "customer", ""); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + case "adjust_credits": + if req.Credits == 0 || req.Credits < -1000000000 || req.Credits > 1000000000 { + http.Error(w, "invalid credit adjustment", http.StatusBadRequest) + return + } + if _, err := store.AdjustCredits(ctx, req.TelegramID, req.Credits, "admin_adjust", nil); err != nil { + http.Error(w, "adjust: "+err.Error(), http.StatusBadRequest) + return + } + default: + http.Error(w, "unknown action", http.StatusBadRequest) + return + } + botWriteJSON(w, map[string]bool{"ok": true}) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Transactions ---------- + +func handleBotTransactions(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + status := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("status"))) + if status != "" && status != "pending" && status != "approved" && status != "expired" && status != "refunded" && status != "error" { + http.Error(w, "invalid status", http.StatusBadRequest) + return + } + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + if limit <= 0 { + limit = 200 + } + if limit > 500 { + limit = 500 + } + txns, err := store.ListTransactions(ctx, status, limit) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, txns) + case http.MethodPost: + var req struct { + ID int `json:"id"` + Action string `json:"action"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == 0 { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + switch req.Action { + case "refund": + if err := store.SetTransactionStatus(ctx, req.ID, "refunded"); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + case "reprocess": + if b := currentBot(); b != nil { + go b.tryFulfill(req.ID) + } else { + http.Error(w, "bot not running", http.StatusServiceUnavailable) + return + } + default: + http.Error(w, "unknown action", http.StatusBadRequest) + return + } + botWriteJSON(w, map[string]bool{"ok": true}) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Settings (bot texts) ---------- + +func handleBotSettings(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + ctx := r.Context() + switch r.Method { + case http.MethodGet: + all, err := store.AllSettings(ctx) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + botWriteJSON(w, all) + case http.MethodPost: + var kv map[string]string + if err := json.NewDecoder(r.Body).Decode(&kv); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + for k, v := range kv { + maxLen, ok := botSettingKeys[k] + if !ok || len(v) > maxLen || botHasControlCharacters(v) { + http.Error(w, "invalid bot setting", http.StatusBadRequest) + return + } + if k == "app_url" && strings.TrimSpace(v) != "" { + u, err := url.ParseRequestURI(strings.TrimSpace(v)) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + http.Error(w, "app_url must be an http or https URL", http.StatusBadRequest) + return + } + } + if err := store.SetSetting(ctx, k, v); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + } + botWriteJSON(w, map[string]bool{"ok": true}) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +// ---------- Connectivity test ---------- + +func handleBotTest(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !botStoreReady(w, store) { + return + } + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + ctx := r.Context() + var req struct { + TelegramToken string `json:"telegram_token"` + MPAccessToken string `json:"mp_access_token"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + cfg, _ := LoadBotConfig(ctx, store) + tgToken := strings.TrimSpace(req.TelegramToken) + mpToken := strings.TrimSpace(req.MPAccessToken) + if cfg != nil { + if tgToken == "" { + tgToken = cfg.TelegramToken + } + if mpToken == "" { + mpToken = cfg.MPAccessToken + } + } + out := map[string]interface{}{} + if tgToken != "" { + name, err := newTGClient(tgToken).getMe(ctx) + if err != nil { + out["telegram_ok"] = false + out["telegram_error"] = err.Error() + } else { + out["telegram_ok"] = true + out["telegram_bot"] = "@" + name + } + } else { + out["telegram_ok"] = false + out["telegram_error"] = "no token configured" + } + if mpToken != "" { + _, err := newMPClient(mpToken).do(ctx, http.MethodGet, "/v1/payment_methods", nil, "") + if err != nil { + out["mp_ok"] = false + out["mp_error"] = err.Error() + } else { + out["mp_ok"] = true + } + } else { + out["mp_ok"] = false + out["mp_error"] = "no token configured" + } + botWriteJSON(w, out) + } +} diff --git a/bot_config.go b/bot_config.go new file mode 100644 index 0000000..d299c65 --- /dev/null +++ b/bot_config.go @@ -0,0 +1,152 @@ +package main + +// bot_config.go — in-memory bot configuration loaded from the bot_config table. +// Secrets are decrypted here and never persisted in plaintext. + +import ( + "context" + "errors" + "strconv" +) + +var errInsufficientCredits = errors.New("insufficient credits") + +func botItoa(n int) string { return strconv.Itoa(n) } + +// BotConfig is the decrypted, ready-to-use bot configuration. +// Telegram always uses long-polling (no webhook). The webhook/polling toggle +// applies only to Mercado Pago payment confirmation (MPConfirmMode). +type BotConfig struct { + Enabled bool + TelegramToken string + MPAccessToken string + MPConfirmMode string // webhook | polling + MPWebhookSecret string + MPPollInterval string + PixExpirationMinutes int + TrialEnabled bool + TrialHours int + TrialMaxConnections int + TrialKind string // ssh | xray + TrialInboundTag string + AdminTelegramIDs []int64 + Currency string + PublicHost string // SSH connection host shown to buyers + XrayPublicHost string // host used to build vless/vmess links +} + +// LoadBotConfig reads the config row and decrypts secrets into a BotConfig. +func LoadBotConfig(ctx context.Context, store *Store) (*BotConfig, error) { + r, err := store.getBotConfigRow(ctx) + if err != nil { + return nil, err + } + tok, err := decryptSecret(r.TelegramTokenEnc) + if err != nil { + return nil, err + } + mp, err := decryptSecret(r.MPAccessTokenEnc) + if err != nil { + return nil, err + } + mpSec, err := decryptSecret(r.MPWebhookSecretEnc) + if err != nil { + return nil, err + } + + cfg := &BotConfig{ + Enabled: r.Enabled, + TelegramToken: tok, + MPAccessToken: mp, + MPConfirmMode: r.MPConfirmMode, + MPWebhookSecret: mpSec, + MPPollInterval: r.MPPollInterval, + PixExpirationMinutes: r.PixExpirationMinutes, + TrialEnabled: r.TrialEnabled, + TrialHours: r.TrialHours, + TrialMaxConnections: r.TrialMaxConnections, + TrialKind: r.TrialKind, + TrialInboundTag: r.TrialInboundTag, + AdminTelegramIDs: r.AdminTelegramIDs, + Currency: r.Currency, + PublicHost: r.PublicHost, + XrayPublicHost: r.XrayPublicHost, + } + cfg.applyDefaults() + return cfg, nil +} + +func (c *BotConfig) applyDefaults() { + if c.MPConfirmMode == "" { + c.MPConfirmMode = "polling" + } + if c.MPPollInterval == "" { + c.MPPollInterval = "20s" + } + if c.PixExpirationMinutes <= 0 { + c.PixExpirationMinutes = 30 + } + if c.TrialHours <= 0 { + c.TrialHours = 1 + } + if c.TrialMaxConnections <= 0 { + c.TrialMaxConnections = 1 + } + if c.TrialKind == "" { + c.TrialKind = "ssh" + } + if c.Currency == "" { + c.Currency = "BRL" + } +} + +func (c *BotConfig) isAdmin(telegramID int64) bool { + for _, id := range c.AdminTelegramIDs { + if id == telegramID { + return true + } + } + return false +} + +// SaveBotConfig persists a BotConfig. Empty secret fields preserve the stored +// value (nil blob → column left unchanged). +func SaveBotConfig(ctx context.Context, store *Store, cfg *BotConfig) error { + cfg.applyDefaults() + row := &botConfigRow{ + Enabled: cfg.Enabled, + TelegramMode: "polling", // Telegram is always long-polling + TelegramWebhookURL: "", + MPConfirmMode: cfg.MPConfirmMode, + MPPollInterval: cfg.MPPollInterval, + PixExpirationMinutes: cfg.PixExpirationMinutes, + TrialEnabled: cfg.TrialEnabled, + TrialHours: cfg.TrialHours, + TrialMaxConnections: cfg.TrialMaxConnections, + TrialKind: cfg.TrialKind, + TrialInboundTag: cfg.TrialInboundTag, + AdminTelegramIDs: cfg.AdminTelegramIDs, + Currency: cfg.Currency, + PublicHost: cfg.PublicHost, + XrayPublicHost: cfg.XrayPublicHost, + } + var tokEnc, mpEnc, mpSecEnc []byte + var err error + if cfg.TelegramToken != "" { + if tokEnc, err = encryptSecret(cfg.TelegramToken); err != nil { + return err + } + } + if cfg.MPAccessToken != "" { + if mpEnc, err = encryptSecret(cfg.MPAccessToken); err != nil { + return err + } + } + if cfg.MPWebhookSecret != "" { + if mpSecEnc, err = encryptSecret(cfg.MPWebhookSecret); err != nil { + return err + } + } + // tgSecEnc is always nil now (no Telegram webhook secret). + return store.saveBotConfigRow(ctx, row, tokEnc, nil, mpEnc, mpSecEnc) +} diff --git a/bot_core.go b/bot_core.go new file mode 100644 index 0000000..e61b3e9 --- /dev/null +++ b/bot_core.go @@ -0,0 +1,267 @@ +package main + +// bot_core.go — Bot lifecycle, Telegram update dispatch, and shared helpers. + +import ( + "context" + "log" + "strings" + "sync" + "time" +) + +// Global bot instance (nil when disabled). Guarded by botMgrMu. +var ( + botMgr *Bot + botMgrMu sync.Mutex +) + +func currentBot() *Bot { + botMgrMu.Lock() + defer botMgrMu.Unlock() + return botMgr +} + +type Bot struct { + store *Store + cfg *BotConfig + tg *tgClient + mp *mpClient + ctx context.Context + cancel context.CancelFunc +} + +func newBot(store *Store, cfg *BotConfig) *Bot { + ctx, cancel := context.WithCancel(context.Background()) + b := &Bot{ + store: store, + cfg: cfg, + tg: newTGClient(cfg.TelegramToken), + ctx: ctx, + cancel: cancel, + } + if cfg.MPAccessToken != "" { + b.mp = newMPClient(cfg.MPAccessToken) + } + return b +} + +// ---------- Lifecycle (called from main.go boot and bot_api.go on save) ---------- + +// startBotService loads config from the DB and starts the bot if enabled. +func startBotService(store *Store) { + if store == nil { + return + } + cfg, err := LoadBotConfig(context.Background(), store) + if err != nil { + log.Printf("[bot] load config: %v", err) + return + } + botMgrMu.Lock() + defer botMgrMu.Unlock() + if botMgr != nil { + botMgr.cancel() + botMgr = nil + } + if !cfg.Enabled { + log.Printf("[bot] disabled") + return + } + if cfg.TelegramToken == "" { + log.Printf("[bot] enabled but no telegram token configured; not starting") + return + } + b := newBot(store, cfg) + botMgr = b + b.start() +} + +// reloadBotService restarts the bot after a config change. +func reloadBotService(store *Store) { startBotService(store) } + +func (b *Bot) start() { + log.Printf("[bot] starting (telegram=long-polling, mp_confirm=%s)", b.cfg.MPConfirmMode) + // Telegram uses long-polling only. Clearing any stale webhook + polling both + // hit the network, so run off the goroutine that holds botMgrMu. + go func() { + _ = b.tg.deleteWebhook(b.ctx) + b.runPolling() + }() + if b.mp != nil && b.cfg.MPConfirmMode == "polling" { + go b.runPaymentPoller() + } +} + +func (b *Bot) stop() { b.cancel() } + +// ---------- Update polling ---------- + +func (b *Bot) runPolling() { + var offset int64 + log.Printf("[bot] long-polling started") + for { + select { + case <-b.ctx.Done(): + log.Printf("[bot] polling stopped") + return + default: + } + ups, err := b.tg.getUpdates(b.ctx, offset, 50) + if err != nil { + if b.ctx.Err() != nil { + return + } + log.Printf("[bot] getUpdates: %v", err) + time.Sleep(3 * time.Second) + continue + } + for i := range ups { + u := ups[i] + if u.UpdateID >= offset { + offset = u.UpdateID + 1 + } + b.handleUpdate(&u) + } + } +} + +// ---------- Dispatch ---------- + +func (b *Bot) handleUpdate(u *tgUpdate) { + defer func() { + if r := recover(); r != nil { + log.Printf("[bot] panic handling update: %v", r) + } + }() + switch { + case u.CallbackQuery != nil: + b.handleCallback(u.CallbackQuery) + case u.Message != nil && u.Message.From != nil: + b.handleMessage(u.Message) + } +} + +func (b *Bot) handleMessage(m *tgMessage) { + b.touchUser(m.From) + text := strings.TrimSpace(m.Text) + switch { + case text == "/start" || text == "/menu" || text == "start": + b.showMainMenu(m.Chat.ID, m.From, 0) + case strings.HasPrefix(text, "/stats") && b.cfg.isAdmin(m.From.ID): + b.cmdAdminStats(m.Chat.ID) + case strings.HasPrefix(text, "/addcredit") && b.cfg.isAdmin(m.From.ID): + b.cmdAdminAddCredit(m.Chat.ID, text) + default: + b.showMainMenu(m.Chat.ID, m.From, 0) + } +} + +func (b *Bot) handleCallback(cb *tgCallbackQuery) { + b.touchUser(&cb.From) + _ = b.tg.answerCallback(b.ctx, cb.ID, "") + if cb.Message == nil { + return + } + chatID := cb.Message.Chat.ID + msgID := cb.Message.MessageID + data := cb.Data + + switch { + case data == "menu:main": + b.showMainMenu(chatID, &cb.From, msgID) + case data == "buy": + b.showPlanList(chatID, msgID, "ssh_or_xray", "buy") + case strings.HasPrefix(data, "buy:"): + b.startPlanPurchase(chatID, &cb.From, data[len("buy:"):], false) + case data == "renew": + b.showRenewList(chatID, &cb.From, msgID) + case strings.HasPrefix(data, "renew:"): + b.startRenew(chatID, &cb.From, msgID, data[len("renew:"):]) + case strings.HasPrefix(data, "rnw:"): + b.startRenewPayment(chatID, &cb.From, data[len("rnw:"):]) + case data == "trial": + b.handleTrial(chatID, &cb.From) + case data == "purchases": + b.showPurchases(chatID, &cb.From, msgID) + case data == "app": + b.showText(chatID, msgID, "app_text", "📥 App: (configure em bot_settings)") + case data == "contact": + b.showText(chatID, msgID, "contact_text", "👤 Contato: (configure em bot_settings)") + case data == "res:menu": + b.showResellerMenu(chatID, &cb.From, msgID) + case data == "res:topup": + b.showCreditPackages(chatID, msgID) + case strings.HasPrefix(data, "res:topup:"): + b.startTopup(chatID, &cb.From, data[len("res:topup:"):]) + case data == "res:create": + b.showPlanList(chatID, msgID, "ssh_or_xray", "res:create") + case strings.HasPrefix(data, "res:create:"): + b.resellerCreateAccount(chatID, &cb.From, data[len("res:create:"):]) + case data == "res:clients": + b.showResellerClients(chatID, &cb.From, msgID) + case strings.HasPrefix(data, "pay:check:"): + b.checkPaymentButton(chatID, &cb.From, data[len("pay:check:"):]) + default: + // unknown — refresh menu + b.showMainMenu(chatID, &cb.From, msgID) + } +} + +// ---------- User helpers ---------- + +func (b *Bot) touchUser(u *tgUser) { + if u == nil { + return + } + _ = b.store.UpsertBotUser(b.ctx, &BotUser{ + TelegramID: u.ID, + Username: u.Username, + FirstName: u.FirstName, + }) +} + +func (b *Bot) botUser(telegramID int64) *BotUser { + u, err := b.store.GetBotUser(b.ctx, telegramID) + if err != nil { + return &BotUser{TelegramID: telegramID, Role: "customer"} + } + return u +} + +// ---------- Message helpers ---------- + +func (b *Bot) send(chatID int64, text string, kb *tgInlineKeyboard) { + if _, err := b.tg.sendMessage(b.ctx, chatID, text, kb); err != nil { + log.Printf("[bot] sendMessage: %v", err) + } +} + +// sendOrEdit edits an existing message if msgID>0, else sends a new one. +func (b *Bot) sendOrEdit(chatID, msgID int64, text string, kb *tgInlineKeyboard) { + if msgID > 0 { + if err := b.tg.editMessageText(b.ctx, chatID, msgID, text, kb); err == nil { + return + } + } + b.send(chatID, text, kb) +} + +func (b *Bot) showText(chatID, msgID int64, key, def string) { + txt := b.store.GetSetting(b.ctx, key, def) + b.sendOrEdit(chatID, msgID, txt, backKeyboard()) +} + +// ---------- Keyboard builders ---------- + +func kb(rows ...[]tgInlineButton) *tgInlineKeyboard { + return &tgInlineKeyboard{InlineKeyboard: rows} +} + +func btn(text, data string) tgInlineButton { return tgInlineButton{Text: text, CallbackData: data} } + +func urlBtn(text, u string) tgInlineButton { return tgInlineButton{Text: text, URL: u} } + +func backKeyboard() *tgInlineKeyboard { + return kb([]tgInlineButton{btn("⬅️ Voltar", "menu:main")}) +} diff --git a/bot_crypto.go b/bot_crypto.go new file mode 100644 index 0000000..c958807 --- /dev/null +++ b/bot_crypto.go @@ -0,0 +1,151 @@ +package main + +// bot_crypto.go — secret encryption for the Telegram/Mercado Pago bot. +// +// Bot tokens (Telegram bot token, Mercado Pago access token, webhook secrets) +// are stored in PostgreSQL encrypted with AES-256-GCM. The 32-byte master key +// lives OUTSIDE the database, so a DB dump alone never reveals the secrets: +// 1) env BOT_MASTER_KEY (64 hex chars), if set; otherwise +// 2) a 0600 key file next to config.json (bot_master.key); otherwise +// 3) generated with crypto/rand on first use and written to that key file. + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" +) + +var ( + botKeyOnce sync.Once + botKey []byte + botKeyErr error +) + +// botMasterKeyPath returns the on-disk location of the AES master key. +func botMasterKeyPath() string { + if globalCfgPath != "" { + return filepath.Join(filepath.Dir(globalCfgPath), "bot_master.key") + } + return "/opt/sshpanel/bot_master.key" +} + +// loadBotMasterKey resolves the 32-byte master key (env → file → generate). +func loadBotMasterKey() ([]byte, error) { + botKeyOnce.Do(func() { + if env := strings.TrimSpace(os.Getenv("BOT_MASTER_KEY")); env != "" { + k, err := hex.DecodeString(env) + if err != nil { + botKeyErr = fmt.Errorf("BOT_MASTER_KEY invalid hex: %w", err) + return + } + if len(k) != 32 { + botKeyErr = fmt.Errorf("BOT_MASTER_KEY must be 32 bytes (64 hex chars), got %d", len(k)) + return + } + botKey = k + return + } + + path := botMasterKeyPath() + data, err := os.ReadFile(path) + if err == nil { + k, derr := hex.DecodeString(strings.TrimSpace(string(data))) + if derr == nil && len(k) == 32 { + botKey = k + return + } + // Refuse to overwrite a bad key file — overwriting would make + // existing ciphertext undecryptable and silently lose secrets. + botKeyErr = fmt.Errorf("bot master key file %s is invalid; refusing to overwrite", path) + return + } + if !errors.Is(err, os.ErrNotExist) { + botKeyErr = fmt.Errorf("read bot master key: %w", err) + return + } + + k := make([]byte, 32) + if _, e := rand.Read(k); e != nil { + botKeyErr = fmt.Errorf("generate bot master key: %w", e) + return + } + if e := os.WriteFile(path, []byte(hex.EncodeToString(k)), 0o600); e != nil { + botKeyErr = fmt.Errorf("write bot master key %s: %w", path, e) + return + } + botKey = k + }) + return botKey, botKeyErr +} + +// encryptSecret encrypts a plaintext secret. Empty input returns nil (no blob). +func encryptSecret(plain string) ([]byte, error) { + if plain == "" { + return nil, nil + } + key, err := loadBotMasterKey() + if err != nil { + return nil, err + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + // Output is nonce || ciphertext(+tag). + return gcm.Seal(nonce, nonce, []byte(plain), nil), nil +} + +// decryptSecret reverses encryptSecret. Empty/nil input returns "". +func decryptSecret(enc []byte) (string, error) { + if len(enc) == 0 { + return "", nil + } + key, err := loadBotMasterKey() + if err != nil { + return "", err + } + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + if len(enc) < gcm.NonceSize() { + return "", fmt.Errorf("ciphertext too short") + } + nonce, ct := enc[:gcm.NonceSize()], enc[gcm.NonceSize():] + pt, err := gcm.Open(nil, nonce, ct, nil) + if err != nil { + return "", fmt.Errorf("decrypt secret: %w", err) + } + return string(pt), nil +} + +// maskSecret returns a log-safe representation of a secret. +func maskSecret(s string) string { + if s == "" { + return "(empty)" + } + if len(s) <= 6 { + return "***" + } + return s[:3] + "***" + s[len(s)-2:] +} diff --git a/bot_flows.go b/bot_flows.go new file mode 100644 index 0000000..70b345c --- /dev/null +++ b/bot_flows.go @@ -0,0 +1,511 @@ +package main + +// bot_flows.go — customer + reseller conversation flows and admin commands. + +import ( + "encoding/base64" + "fmt" + "log" + "strconv" + "strings" + "time" +) + +// ---------- Main menu ---------- + +func (b *Bot) showMainMenu(chatID int64, from *tgUser, msgID int64) { + bu := b.botUser(from.ID) + if bu.Role == "blocked" { + b.sendOrEdit(chatID, msgID, "🚫 Seu acesso foi bloqueado.", nil) + return + } + welcome := b.store.GetSetting(b.ctx, "welcome_text", "") + var text string + if welcome != "" { + text = strings.ReplaceAll(welcome, "{name}", htmlEscape(from.FirstName)) + } else { + text = fmt.Sprintf("😉 Olá %s, seja bem-vindo!\n\n🚀 Aqui você encontra os melhores planos SSH e Xray Premium.\nSelecione uma das opções abaixo:", htmlEscape(from.FirstName)) + } + + var rows [][]tgInlineButton + if b.cfg.TrialEnabled { + rows = append(rows, []tgInlineButton{btn("⏳ Teste Grátis", "trial"), btn("🛍️ Minhas Compras", "purchases")}) + } else { + rows = append(rows, []tgInlineButton{btn("🛍️ Minhas Compras", "purchases")}) + } + rows = append(rows, []tgInlineButton{btn("💎 Comprar Premium", "buy")}) + rows = append(rows, []tgInlineButton{btn("🔄 Renovar", "renew")}) + + appURL := b.store.GetSetting(b.ctx, "app_url", "") + appRow := []tgInlineButton{} + if appURL != "" { + appRow = append(appRow, urlBtn("📥 Baixar APP", appURL)) + } else { + appRow = append(appRow, btn("📥 Baixar APP", "app")) + } + appRow = append(appRow, btn("👤 Contato", "contact")) + rows = append(rows, appRow) + + if bu.Role == "reseller" { + rows = append(rows, []tgInlineButton{btn("👑 Área do Revendedor", "res:menu")}) + } + b.sendOrEdit(chatID, msgID, text, kb(rows...)) +} + +// ---------- Plan list (buy / reseller create) ---------- + +func (b *Bot) showPlanList(chatID, msgID int64, _ string, action string) { + plans, err := b.store.ListPlans(b.ctx, true) + if err != nil || len(plans) == 0 { + b.sendOrEdit(chatID, msgID, "Nenhum plano disponível no momento.", backKeyboard()) + return + } + isReseller := action == "res:create" + var rows [][]tgInlineButton + for _, p := range plans { + icon := "🔒" + if p.Kind == "xray" { + icon = "⚡" + } + var label string + if isReseller { + label = fmt.Sprintf("%s %s — %d créd.", icon, p.Name, p.CreditCost) + } else { + label = fmt.Sprintf("%s %s — %s", icon, p.Name, centsToBRL(p.PriceCents)) + } + rows = append(rows, []tgInlineButton{btn(label, action+":"+botItoa(p.ID))}) + } + rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", backTarget(action))}) + title := "💎 Escolha um plano:" + if isReseller { + title = "➕ Escolha um plano para criar (custo em créditos):" + } + b.sendOrEdit(chatID, msgID, title, kb(rows...)) +} + +func backTarget(action string) string { + if strings.HasPrefix(action, "res:") { + return "res:menu" + } + return "menu:main" +} + +// ---------- Buy ---------- + +func (b *Bot) startPlanPurchase(chatID int64, from *tgUser, planIDStr string, _ bool) { + id, _ := strconv.Atoi(planIDStr) + p, err := b.store.GetPlan(b.ctx, id) + if err != nil { + b.send(chatID, "Plano não encontrado.", backKeyboard()) + return + } + pid := p.ID + b.createAndSendPix(chatID, from, "plan_purchase", "Compra: "+p.Name, p.PriceCents, &pid, nil, 0, "") +} + +// ---------- Renew ---------- + +func (b *Bot) showRenewList(chatID int64, from *tgUser, msgID int64) { + txns, _ := b.store.ListUserTransactions(b.ctx, from.ID, 100) + seen := map[string]bool{} + var rows [][]tgInlineButton + for _, t := range txns { + if t.Status != "approved" || t.TargetUsername == "" || t.PlanID == nil { + continue + } + p, err := b.store.GetPlan(b.ctx, *t.PlanID) + if err != nil { + continue + } + key := p.Kind + ":" + t.TargetUsername + if seen[key] { + continue + } + seen[key] = true + short := "s" + if p.Kind == "xray" { + short = "x" + } + disp := t.TargetUsername + if len(disp) > 16 { + disp = disp[:8] + "…" + } + rows = append(rows, []tgInlineButton{btn("🔄 "+disp+" ("+p.Kind+")", "renew:"+short+":"+t.TargetUsername)}) + } + if len(rows) == 0 { + b.sendOrEdit(chatID, msgID, "Você não tem contas para renovar.", backKeyboard()) + return + } + rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "menu:main")}) + b.sendOrEdit(chatID, msgID, "🔄 Selecione a conta para renovar:", kb(rows...)) +} + +func (b *Bot) startRenew(chatID int64, from *tgUser, msgID int64, target string) { + kind := "ssh" + if strings.HasPrefix(target, "x:") { + kind = "xray" + } + plans, _ := b.store.ListPlans(b.ctx, true) + var rows [][]tgInlineButton + for _, p := range plans { + if p.Kind != kind { + continue + } + label := fmt.Sprintf("%s — %s", p.Name, centsToBRL(p.PriceCents)) + rows = append(rows, []tgInlineButton{btn(label, "rnw:"+botItoa(p.ID)+":"+target)}) + } + if len(rows) == 0 { + b.sendOrEdit(chatID, msgID, "Nenhum plano de renovação disponível.", backKeyboard()) + return + } + rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "renew")}) + b.sendOrEdit(chatID, msgID, "🔄 Escolha a duração da renovação:", kb(rows...)) +} + +func (b *Bot) startRenewPayment(chatID int64, from *tgUser, payload string) { + parts := strings.SplitN(payload, ":", 3) + if len(parts) < 3 { + b.send(chatID, "Renovação inválida.", backKeyboard()) + return + } + id, _ := strconv.Atoi(parts[0]) + renewTarget := parts[1] + ":" + parts[2] // "s:username" or "x:uuid" + p, err := b.store.GetPlan(b.ctx, id) + if err != nil { + b.send(chatID, "Plano não encontrado.", backKeyboard()) + return + } + pid := p.ID + b.createAndSendPix(chatID, from, "plan_renewal", "Renovação: "+p.Name, p.PriceCents, &pid, nil, 0, renewTarget) +} + +// ---------- Trial ---------- + +func (b *Bot) handleTrial(chatID int64, from *tgUser) { + if !b.cfg.TrialEnabled { + b.send(chatID, "Teste grátis indisponível.", backKeyboard()) + return + } + bu := b.botUser(from.ID) + if bu.TrialUsed { + b.send(chatID, "⚠️ Você já utilizou seu teste grátis.", backKeyboard()) + return + } + exp := time.Now().Add(time.Duration(b.cfg.TrialHours) * time.Hour) + if b.cfg.TrialKind == "xray" { + uuid, link, err := createXrayClient(b.ctx, b.store, b.cfg.TrialInboundTag, "", exp, b.cfg.TrialMaxConnections, "", b.cfg.XrayPublicHost) + if err != nil { + log.Printf("[bot] trial xray: %v", err) + b.send(chatID, "❌ Falha ao criar teste. Tente mais tarde.", backKeyboard()) + return + } + _ = b.store.SetBotUserTrialUsed(b.ctx, from.ID) + b.send(chatID, b.formatXrayDelivery("Teste Grátis", uuid, link, exp), backKeyboard()) + return + } + user := genUsername("test") + pass := genPassword() + if err := createSSHUser(b.ctx, b.store, user, pass, exp, b.cfg.TrialMaxConnections, 0, 0, ""); err != nil { + log.Printf("[bot] trial ssh: %v", err) + b.send(chatID, "❌ Falha ao criar teste. Tente mais tarde.", backKeyboard()) + return + } + _ = b.store.SetBotUserTrialUsed(b.ctx, from.ID) + b.send(chatID, b.formatSSHDelivery("Teste Grátis", user, pass, exp), backKeyboard()) +} + +// ---------- Purchases ---------- + +func (b *Bot) showPurchases(chatID int64, from *tgUser, msgID int64) { + txns, _ := b.store.ListUserTransactions(b.ctx, from.ID, 20) + var sb strings.Builder + sb.WriteString("🛍️ Suas Compras\n\n") + count := 0 + for _, t := range txns { + if t.Status == "pending" { + continue + } + count++ + sb.WriteString(fmt.Sprintf("• #%d %s — %s — %s\n", t.ID, txnTypeLabel(t.Type), centsToBRL(t.AmountCents), statusLabel(t.Status))) + if t.TargetUsername != "" && t.Status == "approved" { + sb.WriteString(" conta: " + htmlEscape(t.TargetUsername) + "\n") + } + } + if count == 0 { + sb.WriteString("Nenhuma compra ainda.") + } + b.sendOrEdit(chatID, msgID, sb.String(), backKeyboard()) +} + +// ---------- Reseller ---------- + +func (b *Bot) showResellerMenu(chatID int64, from *tgUser, msgID int64) { + bu := b.botUser(from.ID) + if bu.Role != "reseller" { + b.sendOrEdit(chatID, msgID, "Você não é um revendedor.", backKeyboard()) + return + } + text := fmt.Sprintf("👑 Área do Revendedor\n\n💳 Saldo: %d créditos", bu.CreditBalance) + rows := [][]tgInlineButton{ + {btn("💳 Recarregar Créditos", "res:topup")}, + {btn("➕ Criar Conta", "res:create")}, + {btn("👥 Meus Clientes", "res:clients")}, + {btn("⬅️ Voltar", "menu:main")}, + } + b.sendOrEdit(chatID, msgID, text, kb(rows...)) +} + +func (b *Bot) showCreditPackages(chatID, msgID int64) { + pkgs, _ := b.store.ListCreditPackages(b.ctx, true) + if len(pkgs) == 0 { + b.sendOrEdit(chatID, msgID, "Nenhum pacote de créditos disponível.", kb([]tgInlineButton{btn("⬅️ Voltar", "res:menu")})) + return + } + var rows [][]tgInlineButton + for _, p := range pkgs { + rows = append(rows, []tgInlineButton{btn(fmt.Sprintf("%s — %d créd. — %s", p.Name, p.Credits, centsToBRL(p.PriceCents)), "res:topup:"+botItoa(p.ID))}) + } + rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "res:menu")}) + b.sendOrEdit(chatID, msgID, "💳 Escolha um pacote de créditos:", kb(rows...)) +} + +func (b *Bot) startTopup(chatID int64, from *tgUser, pkgIDStr string) { + id, _ := strconv.Atoi(pkgIDStr) + p, err := b.store.GetCreditPackage(b.ctx, id) + if err != nil { + b.send(chatID, "Pacote não encontrado.", backKeyboard()) + return + } + pid := p.ID + b.createAndSendPix(chatID, from, "credit_topup", "Recarga: "+p.Name, p.PriceCents, nil, &pid, p.Credits, "") +} + +func (b *Bot) resellerCreateAccount(chatID int64, from *tgUser, planIDStr string) { + bu := b.botUser(from.ID) + if bu.Role != "reseller" || bu.LinkedAdminUsername == "" { + b.send(chatID, "Conta de revendedor não configurada.", backKeyboard()) + return + } + id, _ := strconv.Atoi(planIDStr) + p, err := b.store.GetPlan(b.ctx, id) + if err != nil { + b.send(chatID, "Plano não encontrado.", backKeyboard()) + return + } + if bu.CreditBalance < p.CreditCost { + b.send(chatID, fmt.Sprintf("❌ Saldo insuficiente. Necessário %d créditos, você tem %d.", p.CreditCost, bu.CreditBalance), + kb([]tgInlineButton{btn("💳 Recarregar", "res:topup"), btn("⬅️ Voltar", "res:menu")})) + return + } + if owner, ok := adminUsers.get(bu.LinkedAdminUsername); ok && owner.MaxUsers > 0 && + countOwnedQuota(b.ctx, b.store, bu.LinkedAdminUsername) >= owner.MaxUsers { + b.send(chatID, fmt.Sprintf("❌ Limite de contas atingido (%d).", owner.MaxUsers), backKeyboard()) + return + } + // Debit first; refund if provisioning fails. + if _, err := b.store.AdjustCredits(b.ctx, from.ID, -p.CreditCost, "account_create", nil); err != nil { + b.send(chatID, "❌ Não foi possível debitar créditos.", backKeyboard()) + return + } + exp := time.Now().Add(time.Duration(p.Days) * 24 * time.Hour) + var deliver string + if p.Kind == "xray" { + uuid, link, err := createXrayClient(b.ctx, b.store, p.XrayInboundTag, p.XrayProtocol, exp, p.MaxConnections, bu.LinkedAdminUsername, b.cfg.XrayPublicHost) + if err != nil { + _, _ = b.store.AdjustCredits(b.ctx, from.ID, p.CreditCost, "refund", nil) + b.send(chatID, "❌ Falha ao criar conta Xray. Créditos devolvidos.", backKeyboard()) + return + } + deliver = b.formatXrayDelivery(p.Name, uuid, link, exp) + } else { + user := genUsername("r") + pass := genPassword() + if err := createSSHUser(b.ctx, b.store, user, pass, exp, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, bu.LinkedAdminUsername); err != nil { + _, _ = b.store.AdjustCredits(b.ctx, from.ID, p.CreditCost, "refund", nil) + b.send(chatID, "❌ Falha ao criar conta SSH. Créditos devolvidos.", backKeyboard()) + return + } + deliver = b.formatSSHDelivery(p.Name, user, pass, exp) + } + b.send(chatID, deliver+fmt.Sprintf("\n\n💳 Saldo restante: %d créditos", bu.CreditBalance-p.CreditCost), + kb([]tgInlineButton{btn("➕ Criar outra", "res:create"), btn("⬅️ Voltar", "res:menu")})) +} + +func (b *Bot) showResellerClients(chatID int64, from *tgUser, msgID int64) { + bu := b.botUser(from.ID) + if bu.Role != "reseller" || bu.LinkedAdminUsername == "" { + b.sendOrEdit(chatID, msgID, "Conta de revendedor não configurada.", backKeyboard()) + return + } + var sb strings.Builder + sb.WriteString("👥 Seus Clientes\n\n") + n := 0 + for _, u := range userMgr.List() { + if u.Cfg.OwnerUsername == bu.LinkedAdminUsername { + n++ + exp := "sem validade" + if u.ExpiresAt != nil { + exp = u.ExpiresAt.Format("02/01/2006") + } + sb.WriteString(fmt.Sprintf("• SSH %s — %s\n", htmlEscape(u.Cfg.Username), exp)) + if n >= 40 { + break + } + } + } + xs, _ := b.store.ListXrayClientsByOwner(b.ctx, bu.LinkedAdminUsername) + for _, x := range xs { + n++ + exp := "sem validade" + if x.ExpiresAt != nil { + exp = x.ExpiresAt.Format("02/01/2006") + } + sb.WriteString(fmt.Sprintf("• Xray %s — %s\n", htmlEscape(x.UUID), exp)) + if n >= 80 { + break + } + } + if n == 0 { + sb.WriteString("Nenhum cliente ainda.") + } + b.sendOrEdit(chatID, msgID, sb.String(), kb([]tgInlineButton{btn("⬅️ Voltar", "res:menu")})) +} + +// ---------- PIX charge creation + delivery formatting ---------- + +func (b *Bot) createAndSendPix(chatID int64, from *tgUser, ttype, description string, amountCents int, planID, pkgID *int, credits int, renewTarget string) { + if amountCents <= 0 { + b.send(chatID, "❌ Este item não tem preço configurado. Fale com o suporte.", backKeyboard()) + return + } + if b.mp == nil { + b.send(chatID, "❌ Pagamento não configurado no momento. Fale com o suporte.", backKeyboard()) + return + } + exp := time.Now().Add(time.Duration(b.cfg.PixExpirationMinutes) * time.Minute) + pix, err := b.mp.CreatePixPayment(b.ctx, amountCents, description, "", strconv.FormatInt(from.ID, 10), exp, uuidV4()) + if err != nil { + log.Printf("[bot] create pix: %v", err) + b.send(chatID, "❌ Falha ao gerar o pagamento PIX. Tente novamente em instantes.", backKeyboard()) + return + } + txn := &BotTransaction{ + TelegramID: from.ID, + Type: ttype, + PlanID: planID, + PackageID: pkgID, + Credits: credits, + AmountCents: amountCents, + MPPaymentID: pix.PaymentID, + MPQRCode: pix.QRCode, + MPQRBase64: pix.QRBase64, + Status: "pending", + RenewTarget: renewTarget, + ExpiresAt: &exp, + } + if err := b.store.CreateTransaction(b.ctx, txn); err != nil { + log.Printf("[bot] create txn: %v", err) + b.send(chatID, "❌ Erro interno ao registrar o pagamento.", backKeyboard()) + return + } + b.sendPixMessage(chatID, txn, description) +} + +func (b *Bot) sendPixMessage(chatID int64, txn *BotTransaction, description string) { + caption := fmt.Sprintf("💳 Pagamento PIX\n%s\nValor: %s\n⏱ Validade: %d min\n\nEscaneie o QR acima ou use o código copia-e-cola abaixo. A liberação é automática após o pagamento.", + htmlEscape(description), centsToBRL(txn.AmountCents), b.cfg.PixExpirationMinutes) + kbd := kb( + []tgInlineButton{btn("✅ Já paguei / Verificar", "pay:check:"+botItoa(txn.ID))}, + []tgInlineButton{btn("⬅️ Voltar", "menu:main")}, + ) + sent := false + if txn.MPQRBase64 != "" { + if raw, err := base64.StdEncoding.DecodeString(txn.MPQRBase64); err == nil { + if _, err := b.tg.sendPhotoBytes(b.ctx, chatID, raw, "pix.png", caption, kbd); err == nil { + sent = true + } + } + } + if !sent { + b.send(chatID, caption, kbd) + } + if txn.MPQRCode != "" { + b.send(chatID, "📋 PIX Copia e Cola:\n"+htmlEscape(txn.MPQRCode)+"", nil) + } +} + +func (b *Bot) formatSSHDelivery(planName, user, pass string, exp time.Time) string { + host := b.cfg.PublicHost + if host == "" { + host = "(configure o host no painel)" + } + return fmt.Sprintf("✅ %s\n\n🔒 Conta SSH\nHost: %s\nUsuário: %s\nSenha: %s\nValidade: %s", + htmlEscape(planName), htmlEscape(host), htmlEscape(user), htmlEscape(pass), exp.Format("02/01/2006 15:04")) +} + +func (b *Bot) formatXrayDelivery(planName, uuid, link string, exp time.Time) string { + return fmt.Sprintf("✅ %s\n\n⚡ Conta Xray\nUUID: %s\nValidade: %s\n\n🔗 Link de conexão:\n%s", + htmlEscape(planName), htmlEscape(uuid), exp.Format("02/01/2006 15:04"), htmlEscape(link)) +} + +// ---------- Admin commands (in-chat convenience) ---------- + +func (b *Bot) cmdAdminStats(chatID int64) { + users, _ := b.store.ListBotUsers(b.ctx) + pend, _ := b.store.ListPendingTransactions(b.ctx) + b.send(chatID, fmt.Sprintf("📊 Estatísticas\nUsuários do bot: %d\nPagamentos pendentes: %d\nContas SSH ativas: %d", + len(users), len(pend), len(userMgr.List())), nil) +} + +func (b *Bot) cmdAdminAddCredit(chatID int64, text string) { + f := strings.Fields(text) + if len(f) < 3 { + b.send(chatID, "Uso: /addcredit <telegram_id> <quantidade>", nil) + return + } + tid, _ := strconv.ParseInt(f[1], 10, 64) + amt, _ := strconv.Atoi(f[2]) + bal, err := b.store.AdjustCredits(b.ctx, tid, amt, "admin_adjust", nil) + if err != nil { + b.send(chatID, "Erro: "+err.Error(), nil) + return + } + b.send(chatID, fmt.Sprintf("✅ Ajuste aplicado. Novo saldo de %d: %d créditos", tid, bal), nil) + b.notify(tid, fmt.Sprintf("💳 Seu saldo foi ajustado em %+d créditos. Saldo atual: %d", amt, bal)) +} + +func (b *Bot) notify(telegramID int64, text string) { + if _, err := b.tg.sendMessage(b.ctx, telegramID, text, nil); err != nil { + log.Printf("[bot] notify %d: %v", telegramID, err) + } +} + +// ---------- labels ---------- + +func txnTypeLabel(t string) string { + switch t { + case "plan_purchase": + return "Compra" + case "plan_renewal": + return "Renovação" + case "credit_topup": + return "Recarga" + } + return t +} + +func statusLabel(s string) string { + switch s { + case "approved": + return "✅ pago" + case "pending": + return "⏳ pendente" + case "expired": + return "⌛ expirado" + case "refunded": + return "↩️ estornado" + case "error": + return "❌ erro" + } + return s +} diff --git a/bot_mercadopago.go b/bot_mercadopago.go new file mode 100644 index 0000000..250ad60 --- /dev/null +++ b/bot_mercadopago.go @@ -0,0 +1,242 @@ +package main + +// bot_mercadopago.go — Mercado Pago PIX client + inbound webhook handler. +// Built on net/http; no third-party dependency. + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "strconv" + "strings" + "time" +) + +const mpAPIBase = "https://api.mercadopago.com" + +type mpClient struct { + accessToken string + hc *http.Client +} + +func newMPClient(accessToken string) *mpClient { + return &mpClient{accessToken: accessToken, hc: &http.Client{Timeout: 25 * time.Second}} +} + +// mpPixResult holds what the bot needs to show the buyer. +type mpPixResult struct { + PaymentID string + QRCode string // copy-and-paste PIX string + QRBase64 string // PNG image, base64 (no data: prefix) + Status string +} + +// CreatePixPayment creates a PIX charge and returns the QR data. +// amountCents is BRL cents; expiresAt bounds the QR validity. +func (c *mpClient) CreatePixPayment(ctx context.Context, amountCents int, description, payerEmail, externalRef string, expiresAt time.Time, idempotencyKey string) (*mpPixResult, error) { + if payerEmail == "" { + payerEmail = "comprador@example.com" + } + body := map[string]interface{}{ + "transaction_amount": float64(amountCents) / 100.0, + "description": description, + "payment_method_id": "pix", + "payer": map[string]interface{}{"email": payerEmail}, + "date_of_expiration": expiresAt.Format("2006-01-02T15:04:05.000-07:00"), + "external_reference": externalRef, + } + raw, err := c.do(ctx, http.MethodPost, "/v1/payments", body, idempotencyKey) + if err != nil { + return nil, err + } + var resp struct { + ID json.Number `json:"id"` + Status string `json:"status"` + PointOfInteraction struct { + TransactionData struct { + QRCode string `json:"qr_code"` + QRCodeBase64 string `json:"qr_code_base64"` + } `json:"transaction_data"` + } `json:"point_of_interaction"` + } + if err := json.Unmarshal(raw, &resp); err != nil { + return nil, fmt.Errorf("mp create payment: parse: %w", err) + } + if resp.ID.String() == "" { + return nil, fmt.Errorf("mp create payment: no id in response: %s", string(raw)) + } + return &mpPixResult{ + PaymentID: resp.ID.String(), + QRCode: resp.PointOfInteraction.TransactionData.QRCode, + QRBase64: resp.PointOfInteraction.TransactionData.QRCodeBase64, + Status: resp.Status, + }, nil +} + +// GetPaymentStatus returns the current status of a payment (e.g. "approved"). +func (c *mpClient) GetPaymentStatus(ctx context.Context, paymentID string) (string, error) { + raw, err := c.do(ctx, http.MethodGet, "/v1/payments/"+paymentID, nil, "") + if err != nil { + return "", err + } + var resp struct { + Status string `json:"status"` + } + if err := json.Unmarshal(raw, &resp); err != nil { + return "", err + } + return resp.Status, nil +} + +func (c *mpClient) do(ctx context.Context, method, path string, body interface{}, idempotencyKey string) ([]byte, error) { + var rdr io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + return nil, err + } + rdr = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, mpAPIBase+path, rdr) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+c.accessToken) + req.Header.Set("Content-Type", "application/json") + if idempotencyKey != "" { + req.Header.Set("X-Idempotency-Key", idempotencyKey) + } + resp, err := c.hc.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if resp.StatusCode >= 300 { + return nil, fmt.Errorf("mercado pago %s %s: http %d: %s", method, path, resp.StatusCode, string(data)) + } + return data, nil +} + +// verifyMPSignature validates the x-signature header per Mercado Pago's spec. +// Manifest: "id:;request-id:;ts:;" HMAC-SHA256(secret). +func verifyMPSignature(xSignature, xRequestID, dataID, secret string) bool { + if secret == "" { + return false + } + var ts, v1 string + for _, part := range strings.Split(xSignature, ",") { + kv := strings.SplitN(strings.TrimSpace(part), "=", 2) + if len(kv) != 2 { + continue + } + switch strings.TrimSpace(kv[0]) { + case "ts": + ts = strings.TrimSpace(kv[1]) + case "v1": + v1 = strings.TrimSpace(kv[1]) + } + } + if ts == "" || v1 == "" { + return false + } + if timestamp, err := strconv.ParseInt(ts, 10, 64); err != nil || timestamp <= 0 { + return false + } + parts := make([]string, 0, 3) + if dataID != "" { + parts = append(parts, "id:"+strings.ToLower(dataID)) + } + if xRequestID != "" { + parts = append(parts, "request-id:"+xRequestID) + } + parts = append(parts, "ts:"+ts) + manifest := strings.Join(parts, ";") + ";" + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(manifest)) + expected := hex.EncodeToString(mac.Sum(nil)) + return hmac.Equal([]byte(expected), []byte(v1)) +} + +// handleMPWebhook is the public endpoint Mercado Pago calls on payment events. +// It never trusts the body: it re-fetches the payment and fulfills idempotently. +func handleMPWebhook(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + b := currentBot() + if b == nil { + w.WriteHeader(http.StatusOK) // bot disabled; acknowledge to stop retries + return + } + // Only honor webhooks when confirmation mode is "webhook". In polling mode + // the poller drives fulfillment; ignore unsolicited posts to this endpoint. + if b.cfg.MPConfirmMode != "webhook" { + w.WriteHeader(http.StatusOK) + return + } + // Extract the payment id from body or query. + dataID := r.URL.Query().Get("data.id") + if dataID == "" { + dataID = r.URL.Query().Get("id") + } + signatureDataID := dataID + var payload struct { + Type string `json:"type"` + Action string `json:"action"` + Data struct { + ID json.Number `json:"id"` + } `json:"data"` + } + r.Body = http.MaxBytesReader(w, r.Body, 1<<20) + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "invalid webhook body", http.StatusRequestEntityTooLarge) + return + } + if len(body) > 0 { + _ = json.Unmarshal(body, &payload) + if dataID == "" { + dataID = payload.Data.ID.String() + } + } + if dataID == "" { + w.WriteHeader(http.StatusOK) + return + } + if len(dataID) > 32 { + w.WriteHeader(http.StatusBadRequest) + return + } + for _, char := range dataID { + if char < '0' || char > '9' { + w.WriteHeader(http.StatusBadRequest) + return + } + } + + if !verifyMPSignature(r.Header.Get("x-signature"), r.Header.Get("x-request-id"), signatureDataID, b.cfg.MPWebhookSecret) { + log.Printf("[bot] MP webhook: invalid signature for payment %s", dataID) + w.WriteHeader(http.StatusUnauthorized) + return + } + + // Acknowledge immediately; process in the background so MP doesn't time out. + go b.processPaymentByMPID(dataID) + w.WriteHeader(http.StatusOK) +} + +// centsToBRL formats cents as "R$ 12,34". +func centsToBRL(cents int) string { + reais := cents / 100 + cent := cents % 100 + return "R$ " + strconv.Itoa(reais) + "," + fmt.Sprintf("%02d", cent) +} diff --git a/bot_payments.go b/bot_payments.go new file mode 100644 index 0000000..706be7c --- /dev/null +++ b/bot_payments.go @@ -0,0 +1,237 @@ +package main + +// bot_payments.go — payment polling, webhook processing, and idempotent delivery. + +import ( + "fmt" + "log" + "strconv" + "strings" + "time" +) + +// ---------- Polling mode ---------- + +func (b *Bot) runPaymentPoller() { + d, err := time.ParseDuration(b.cfg.MPPollInterval) + if err != nil || d < 5*time.Second { + d = 20 * time.Second + } + t := time.NewTicker(d) + defer t.Stop() + log.Printf("[bot] payment poller started (interval=%s)", d) + for { + select { + case <-b.ctx.Done(): + log.Printf("[bot] payment poller stopped") + return + case <-t.C: + b.pollPending() + } + } +} + +func (b *Bot) pollPending() { + txns, err := b.store.ListPendingTransactions(b.ctx) + if err != nil { + log.Printf("[bot] poll list: %v", err) + return + } + now := time.Now() + for _, txn := range txns { + if txn.ExpiresAt != nil && now.After(*txn.ExpiresAt) { + _ = b.store.SetTransactionStatus(b.ctx, txn.ID, "expired") + b.notify(txn.TelegramID, fmt.Sprintf("⌛ O PIX do pedido #%d expirou. Gere um novo pagamento se ainda quiser.", txn.ID)) + continue + } + if b.mp == nil { + continue + } + status, err := b.mp.GetPaymentStatus(b.ctx, txn.MPPaymentID) + if err != nil { + continue + } + if status == "approved" { + b.tryFulfill(txn.ID) + } + } +} + +// ---------- Webhook mode ---------- + +// processPaymentByMPID is invoked from the Mercado Pago webhook handler. +func (b *Bot) processPaymentByMPID(mpID string) { + txn, err := b.store.GetTransactionByMPID(b.ctx, mpID) + if err != nil { + log.Printf("[bot] webhook: no txn for mp payment %s: %v", mpID, err) + return + } + if b.mp == nil { + return + } + status, err := b.mp.GetPaymentStatus(b.ctx, mpID) + if err != nil { + log.Printf("[bot] webhook: get status %s: %v", mpID, err) + return + } + if status == "approved" { + b.tryFulfill(txn.ID) + } +} + +// ---------- Idempotent fulfillment ---------- + +// tryFulfill flips the txn to approved exactly once, then delivers. +func (b *Bot) tryFulfill(txnID int) { + ok, err := b.store.MarkTransactionApproved(b.ctx, txnID) + if err != nil { + log.Printf("[bot] mark approved %d: %v", txnID, err) + return + } + if !ok { + return // already fulfilled by another path + } + txn, err := b.store.GetTransaction(b.ctx, txnID) + if err != nil { + log.Printf("[bot] fulfill get txn %d: %v", txnID, err) + return + } + b.fulfillTransaction(txn) +} + +func (b *Bot) fulfillTransaction(txn *BotTransaction) { + switch txn.Type { + case "credit_topup": + bal, err := b.store.AdjustCredits(b.ctx, txn.TelegramID, txn.Credits, "topup", &txn.ID) + if err != nil { + log.Printf("[bot] topup credit %d: %v", txn.ID, err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao creditar. Contate o suporte.") + return + } + b.notify(txn.TelegramID, fmt.Sprintf("✅ Recarga aprovada! +%d créditos.\n💳 Saldo atual: %d créditos.", txn.Credits, bal)) + case "plan_renewal": + b.fulfillRenewal(txn) + default: + b.fulfillPurchase(txn) + } +} + +func (b *Bot) fulfillPurchase(txn *BotTransaction) { + if txn.PlanID == nil { + return + } + p, err := b.store.GetPlan(b.ctx, *txn.PlanID) + if err != nil { + log.Printf("[bot] fulfill purchase: plan %v: %v", txn.PlanID, err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas o plano não foi encontrado. Contate o suporte.") + return + } + exp := time.Now().Add(time.Duration(p.Days) * 24 * time.Hour) + if p.Kind == "xray" { + uuid, link, err := createXrayClient(b.ctx, b.store, p.XrayInboundTag, p.XrayProtocol, exp, p.MaxConnections, "", b.cfg.XrayPublicHost) + if err != nil { + log.Printf("[bot] fulfill xray: %v", err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao criar a conta Xray. Contate o suporte.") + return + } + _ = b.store.SetTransactionTarget(b.ctx, txn.ID, uuid) + b.notify(txn.TelegramID, b.formatXrayDelivery(p.Name, uuid, link, exp)) + return + } + user := genUsername("ssh") + pass := genPassword() + if err := createSSHUser(b.ctx, b.store, user, pass, exp, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, ""); err != nil { + log.Printf("[bot] fulfill ssh: %v", err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao criar a conta SSH. Contate o suporte.") + return + } + _ = b.store.SetTransactionTarget(b.ctx, txn.ID, user) + b.notify(txn.TelegramID, b.formatSSHDelivery(p.Name, user, pass, exp)) +} + +func (b *Bot) fulfillRenewal(txn *BotTransaction) { + if txn.PlanID == nil || txn.RenewTarget == "" { + return + } + p, err := b.store.GetPlan(b.ctx, *txn.PlanID) + if err != nil { + return + } + parts := strings.SplitN(txn.RenewTarget, ":", 2) + if len(parts) < 2 { + return + } + kind, id := parts[0], parts[1] + base := time.Now() + add := time.Duration(p.Days) * 24 * time.Hour + + if kind == "x" { + newExp := base.Add(add) + if meta, err := b.store.GetXrayClientMeta(b.ctx, id); err == nil && meta.ExpiresAt != nil && meta.ExpiresAt.After(base) { + newExp = meta.ExpiresAt.Add(add) + } + if err := renewXrayClient(b.ctx, b.store, id, newExp); err != nil { + log.Printf("[bot] renew xray %s: %v", id, err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao renovar. Contate o suporte.") + return + } + _ = b.store.SetTransactionTarget(b.ctx, txn.ID, id) + b.notify(txn.TelegramID, fmt.Sprintf("✅ %s renovado!\n⚡ Xray %s\nNova validade: %s", + htmlEscape(p.Name), htmlEscape(id), newExp.Format("02/01/2006 15:04"))) + return + } + + newExp := base.Add(add) + if u, ok := userMgr.Get(id); ok && u.ExpiresAt != nil && u.ExpiresAt.After(base) { + newExp = u.ExpiresAt.Add(add) + } + if err := renewSSHUser(b.ctx, b.store, id, newExp); err != nil { + log.Printf("[bot] renew ssh %s: %v", id, err) + b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao renovar. Contate o suporte.") + return + } + _ = b.store.SetTransactionTarget(b.ctx, txn.ID, id) + b.notify(txn.TelegramID, fmt.Sprintf("✅ %s renovado!\n🔒 SSH %s\nNova validade: %s", + htmlEscape(p.Name), htmlEscape(id), newExp.Format("02/01/2006 15:04"))) +} + +// ---------- "Verificar" button ---------- + +func (b *Bot) checkPaymentButton(chatID int64, from *tgUser, txnIDStr string) { + id, _ := strconv.Atoi(txnIDStr) + txn, err := b.store.GetTransaction(b.ctx, id) + if err != nil { + b.send(chatID, "Pagamento não encontrado.", backKeyboard()) + return + } + if txn.TelegramID != from.ID { + b.send(chatID, "Pagamento inválido.", backKeyboard()) + return + } + switch txn.Status { + case "approved": + b.send(chatID, "✅ Pagamento já confirmado! Veja em 🛍️ Minhas Compras.", backKeyboard()) + return + case "expired": + b.send(chatID, "⌛ Este PIX expirou. Gere um novo pagamento.", backKeyboard()) + return + case "refunded": + b.send(chatID, "Este pagamento foi estornado.", backKeyboard()) + return + } + if b.mp == nil { + b.send(chatID, "Pagamento não configurado.", backKeyboard()) + return + } + status, err := b.mp.GetPaymentStatus(b.ctx, txn.MPPaymentID) + if err != nil { + b.send(chatID, "Não foi possível verificar agora. Tente novamente em instantes.", backKeyboard()) + return + } + if status == "approved" { + b.tryFulfill(txn.ID) // delivers via notify + return + } + b.send(chatID, "⏱ Pagamento ainda não identificado. Assim que cair, a liberação é automática.", + kb([]tgInlineButton{btn("🔄 Verificar novamente", "pay:check:"+botItoa(txn.ID)), btn("⬅️ Voltar", "menu:main")})) +} diff --git a/bot_provision.go b/bot_provision.go new file mode 100644 index 0000000..65337da --- /dev/null +++ b/bot_provision.go @@ -0,0 +1,292 @@ +package main + +// bot_provision.go — bridges the bot to the panel's account creation. +// SSH: Store.UpsertUser. Xray: xrayMgr.AddXrayClient + UpsertXrayClientMeta. + +import ( + "context" + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "log" + "net" + "net/url" + "strconv" + "strings" + "time" +) + +// ---------- credential generation ---------- + +const credAlphabet = "abcdefghijkmnpqrstuvwxyz23456789" + +func randString(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + // extremely unlikely; fall back to a fixed-length timestamp-free filler + for i := range b { + b[i] = credAlphabet[0] + } + return string(b) + } + for i := range b { + b[i] = credAlphabet[int(b[i])%len(credAlphabet)] + } + return string(b) +} + +func genUsername(prefix string) string { + if prefix == "" { + prefix = "ssh" + } + return prefix + randString(6) +} + +func genPassword() string { return randString(10) } + +func uuidV4() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} + +// ---------- SSH ---------- + +func createSSHUser(ctx context.Context, store *Store, username, password string, expiresAt time.Time, maxConns, upMbps, downMbps int, owner string) error { + cfg := UserConfig{ + Username: username, + Password: password, + MaxConnections: maxConns, + ExpiresAt: expiresAt.UTC().Format(time.RFC3339), + LimitMbpsUp: upMbps, + LimitMbpsDown: downMbps, + OwnerUsername: owner, + } + if err := store.UpsertUser(ctx, cfg); err != nil { + return err + } + reloadUsersFromDB(ctx, store) + return nil +} + +// renewSSHUser extends an existing SSH account's expiry, preserving credentials. +func renewSSHUser(ctx context.Context, store *Store, username string, newExpiry time.Time) error { + u, ok := userMgr.Get(username) + if !ok { + return fmt.Errorf("conta SSH %q não encontrada", username) + } + cfg := u.Cfg + cfg.ExpiresAt = newExpiry.UTC().Format(time.RFC3339) + if err := store.UpsertUser(ctx, cfg); err != nil { + return err + } + reloadUsersFromDB(ctx, store) + return nil +} + +// ---------- Xray ---------- + +func createXrayClient(ctx context.Context, store *Store, inboundTag, protocol string, expiresAt time.Time, maxConns int, owner, publicHost string) (uuid, link string, err error) { + if inboundTag == "" { + return "", "", fmt.Errorf("plano Xray sem inbound configurado") + } + uuid = uuidV4() + email := "bot-" + uuid[:8] + if err = xrayMgr.AddXrayClient(inboundTag, uuid, email); err != nil { + return "", "", err + } + exp := expiresAt + meta := XrayClientMeta{ + UUID: uuid, + Name: email, + Email: email, + InboundTag: inboundTag, + OwnerUsername: owner, + MaxConns: maxConns, + ExpiresAt: &exp, + } + if e := store.UpsertXrayClientMeta(ctx, meta); e != nil { + // The client is already live in Xray; a metadata failure must not + // abort delivery. Log and continue. + log.Printf("[bot] xray meta save for %s: %v", uuid, e) + } + xrayMgr.restartIfExternalRunning() + link = buildXrayLink(inboundTag, protocol, uuid, publicHost, email) + return uuid, link, nil +} + +func renewXrayClient(ctx context.Context, store *Store, uuid string, newExpiry time.Time) error { + meta, err := store.GetXrayClientMeta(ctx, uuid) + if err != nil { + return fmt.Errorf("cliente Xray não encontrado: %w", err) + } + exp := newExpiry + meta.ExpiresAt = &exp + return store.UpsertXrayClientMeta(ctx, *meta) +} + +// ---------- Xray connection link ---------- + +type xrayInboundDetail struct { + Protocol string + Port int + Network string + Security string + Path string + Host string + SNI string + ServiceName string +} + +// inboundDetail reads streamSettings for an inbound from the raw Xray config. +func (m *XrayManager) inboundDetail(tag string) (*xrayInboundDetail, error) { + m.mu.Lock() + defer m.mu.Unlock() + data, err := m.readConfigLocked() + if err != nil { + return nil, err + } + var cfg struct { + Inbounds []json.RawMessage `json:"inbounds"` + } + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, err + } + for _, raw := range cfg.Inbounds { + var ib struct { + Tag string `json:"tag"` + Protocol string `json:"protocol"` + Port json.RawMessage `json:"port"` + SharedPort bool `json:"dragoncoreSharedPort"` + StreamSettings map[string]interface{} `json:"streamSettings"` + } + if err := json.Unmarshal(raw, &ib); err != nil { + continue + } + if ib.Tag != tag { + continue + } + d := &xrayInboundDetail{Protocol: strings.ToLower(ib.Protocol)} + var pnum int + if json.Unmarshal(ib.Port, &pnum) == nil { + d.Port = pnum + } else { + var pstr string + if json.Unmarshal(ib.Port, &pstr) == nil { + d.Port, _ = strconv.Atoi(pstr) + } + } + if ss := ib.StreamSettings; ss != nil { + d.Network, _ = ss["network"].(string) + d.Security, _ = ss["security"].(string) + d.Path, d.Host, d.ServiceName = extractStreamParams(ss, d.Network) + if tls, ok := ss["tlsSettings"].(map[string]interface{}); ok { + d.SNI, _ = tls["serverName"].(string) + } + if rl, ok := ss["realitySettings"].(map[string]interface{}); ok { + if sn, _ := rl["serverNames"].([]interface{}); len(sn) > 0 { + d.SNI, _ = sn[0].(string) + } + } + } + if ib.SharedPort { + // The public listener terminates TLS before the native emulator. + // Connection links describe the client-facing socket instead of the + // internal streamSettings security (which must remain "none"). + if panel := getGlobalCfg(); panel != nil { + if len(panel.TLSForwarders) > 0 { + selected := panel.TLSForwarders[0].Listen + for _, fwd := range panel.TLSForwarders { + if strings.HasSuffix(fwd.Listen, ":443") { selected = fwd.Listen; break } + } + if _, port, err := net.SplitHostPort(selected); err == nil { + if value, err := strconv.Atoi(port); err == nil { d.Port = value; d.Security = "tls" } + } + } else if _, port, err := net.SplitHostPort(panel.Listen); err == nil { + if value, err := strconv.Atoi(port); err == nil { d.Port = value; d.Security = "none" } + } + } + } + return d, nil + } + return nil, fmt.Errorf("inbound %q não encontrado", tag) +} + +func extractStreamParams(ss map[string]interface{}, network string) (path, host, serviceName string) { + get := func(key, field string) string { + if sub, ok := ss[key].(map[string]interface{}); ok { + v, _ := sub[field].(string) + return v + } + return "" + } + switch network { + case "ws": + return get("wsSettings", "path"), get("wsSettings", "host"), "" + case "xhttp": + return get("xhttpSettings", "path"), get("xhttpSettings", "host"), "" + case "httpupgrade": + return get("httpupgradeSettings", "path"), get("httpupgradeSettings", "host"), "" + case "grpc": + return "", "", get("grpcSettings", "serviceName") + case "http", "h2": + return get("httpSettings", "path"), get("httpSettings", "host"), "" + } + return "", "", "" +} + +// buildXrayLink assembles a shareable connection URI. Best-effort: if the config +// can't be read it still returns a minimal link with host/port/uuid. +func buildXrayLink(inboundTag, protocol, uuid, publicHost, label string) string { + d, err := xrayMgr.inboundDetail(inboundTag) + if err != nil || d == nil { + if protocol == "" { + protocol = "vless" + } + return fmt.Sprintf("%s://%s@%s#%s", protocol, uuid, publicHost, url.QueryEscape(label)) + } + if protocol == "" { + protocol = d.Protocol + } + host := publicHost + if host == "" { + host = d.SNI + } + addr := fmt.Sprintf("%s:%d", host, d.Port) + + q := url.Values{} + if d.Network != "" { + q.Set("type", d.Network) + } + if d.Security != "" { + q.Set("security", d.Security) + } + if d.Path != "" { + q.Set("path", d.Path) + } + if d.Host != "" { + q.Set("host", d.Host) + } + if d.SNI != "" { + q.Set("sni", d.SNI) + } + if d.ServiceName != "" { + q.Set("serviceName", d.ServiceName) + } + + switch protocol { + case "vmess": + conf := map[string]interface{}{ + "v": "2", "ps": label, "add": host, "port": strconv.Itoa(d.Port), + "id": uuid, "aid": "0", "scy": "auto", "net": d.Network, + "type": "none", "host": d.Host, "path": d.Path, "tls": d.Security, "sni": d.SNI, + } + b, _ := json.Marshal(conf) + return "vmess://" + base64.StdEncoding.EncodeToString(b) + default: // vless, trojan + return fmt.Sprintf("%s://%s@%s?%s#%s", protocol, uuid, addr, q.Encode(), url.QueryEscape(label)) + } +} diff --git a/bot_store.go b/bot_store.go new file mode 100644 index 0000000..e99fa56 --- /dev/null +++ b/bot_store.go @@ -0,0 +1,672 @@ +package main + +// bot_store.go — PostgreSQL persistence for the Telegram sales bot. +// +// Tables (all created idempotently by EnsureBotSchema): +// bot_users — Telegram customers/resellers +// bot_plans — sellable SSH/Xray plans +// bot_credit_packages — reseller credit top-up packages +// bot_transactions — PIX payments (Mercado Pago) +// bot_credits_ledger — auditable credit movements +// bot_settings — editable bot texts (key/value) +// bot_config — single-row bot config with encrypted secrets + +import ( + "context" + "database/sql" + "time" + + "github.com/lib/pq" +) + +// ---------- Models ---------- + +type BotUser struct { + TelegramID int64 + Username string + FirstName string + Role string // customer | reseller | blocked + LinkedAdminUsername string + CreditBalance int + TrialUsed bool + CreatedAt time.Time + LastSeenAt time.Time +} + +type BotPlan struct { + ID int + Name string + Kind string // ssh | xray + Days int + MaxConnections int + LimitMbpsUp int + LimitMbpsDown int + XrayInboundTag string + XrayProtocol string + PriceCents int + CreditCost int + ServerID string + IsActive bool + SortOrder int +} + +type BotCreditPackage struct { + ID int + Name string + Credits int + PriceCents int + IsActive bool + SortOrder int +} + +type BotTransaction struct { + ID int + TelegramID int64 + Type string // plan_purchase | plan_renewal | credit_topup + PlanID *int + PackageID *int + Credits int + AmountCents int + MPPaymentID string + MPQRCode string + MPQRBase64 string + Status string // pending | approved | expired | refunded | error + TargetUsername string // account/uuid created or renewed + RenewTarget string // for renewals: existing account/uuid to extend + CreatedAt time.Time + PaidAt *time.Time + ExpiresAt *time.Time +} + +type BotLedgerEntry struct { + ID int + TelegramID int64 + Delta int + Reason string + RefTxnID *int + BalanceAfter int + CreatedAt time.Time +} + +// ---------- Schema ---------- + +func (s *Store) EnsureBotSchema(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS bot_users ( + telegram_id BIGINT PRIMARY KEY, + username TEXT NOT NULL DEFAULT '', + first_name TEXT NOT NULL DEFAULT '', + role TEXT NOT NULL DEFAULT 'customer', + linked_admin_username TEXT NOT NULL DEFAULT '', + credit_balance INT NOT NULL DEFAULT 0, + trial_used BOOLEAN NOT NULL DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `CREATE TABLE IF NOT EXISTS bot_plans ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL DEFAULT 'ssh', + days INT NOT NULL DEFAULT 30, + max_connections INT NOT NULL DEFAULT 1, + limit_mbps_up INT NOT NULL DEFAULT 0, + limit_mbps_down INT NOT NULL DEFAULT 0, + xray_inbound_tag TEXT NOT NULL DEFAULT '', + xray_protocol TEXT NOT NULL DEFAULT '', + price_cents INT NOT NULL DEFAULT 0, + credit_cost INT NOT NULL DEFAULT 1, + server_id TEXT NOT NULL DEFAULT '', + is_active BOOLEAN NOT NULL DEFAULT true, + sort_order INT NOT NULL DEFAULT 0 + )`, + `CREATE TABLE IF NOT EXISTS bot_credit_packages ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + credits INT NOT NULL DEFAULT 0, + price_cents INT NOT NULL DEFAULT 0, + is_active BOOLEAN NOT NULL DEFAULT true, + sort_order INT NOT NULL DEFAULT 0 + )`, + `CREATE TABLE IF NOT EXISTS bot_transactions ( + id SERIAL PRIMARY KEY, + telegram_id BIGINT NOT NULL, + type TEXT NOT NULL, + plan_id INT, + package_id INT, + credits INT NOT NULL DEFAULT 0, + amount_cents INT NOT NULL DEFAULT 0, + mp_payment_id TEXT NOT NULL DEFAULT '', + mp_qr_code TEXT NOT NULL DEFAULT '', + mp_qr_base64 TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + target_username TEXT NOT NULL DEFAULT '', + renew_target TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + paid_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS bot_transactions_mp_payment_id_uidx + ON bot_transactions (mp_payment_id) WHERE mp_payment_id <> ''`, + `CREATE TABLE IF NOT EXISTS bot_credits_ledger ( + id SERIAL PRIMARY KEY, + telegram_id BIGINT NOT NULL, + delta INT NOT NULL, + reason TEXT NOT NULL DEFAULT '', + ref_transaction_id INT, + balance_after INT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `CREATE TABLE IF NOT EXISTS bot_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL DEFAULT '' + )`, + `CREATE TABLE IF NOT EXISTS bot_config ( + id INT PRIMARY KEY DEFAULT 1 CHECK (id = 1), + enabled BOOLEAN NOT NULL DEFAULT false, + telegram_mode TEXT NOT NULL DEFAULT 'polling', + telegram_webhook_url TEXT NOT NULL DEFAULT '', + mp_confirm_mode TEXT NOT NULL DEFAULT 'polling', + mp_poll_interval TEXT NOT NULL DEFAULT '20s', + pix_expiration_minutes INT NOT NULL DEFAULT 30, + trial_enabled BOOLEAN NOT NULL DEFAULT true, + trial_hours INT NOT NULL DEFAULT 1, + trial_max_connections INT NOT NULL DEFAULT 1, + trial_kind TEXT NOT NULL DEFAULT 'ssh', + trial_inbound_tag TEXT NOT NULL DEFAULT '', + admin_telegram_ids BIGINT[] NOT NULL DEFAULT '{}', + currency TEXT NOT NULL DEFAULT 'BRL', + public_host TEXT NOT NULL DEFAULT '', + xray_public_host TEXT NOT NULL DEFAULT '', + telegram_token_enc BYTEA, + telegram_webhook_secret_enc BYTEA, + mp_access_token_enc BYTEA, + mp_webhook_secret_enc BYTEA, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `INSERT INTO bot_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return nil +} + +// ---------- bot_users ---------- + +// UpsertBotUser inserts a user or refreshes username/first_name/last_seen. +// Role, credits, linkage and trial_used are preserved on update. +func (s *Store) UpsertBotUser(ctx context.Context, u *BotUser) error { + _, err := s.db.ExecContext(ctx, ` + INSERT INTO bot_users (telegram_id, username, first_name, last_seen_at) + VALUES ($1, $2, $3, NOW()) + ON CONFLICT (telegram_id) DO UPDATE + SET username = EXCLUDED.username, + first_name = EXCLUDED.first_name, + last_seen_at = NOW()`, + u.TelegramID, u.Username, u.FirstName) + return err +} + +func scanBotUser(row interface{ Scan(...interface{}) error }) (*BotUser, error) { + var u BotUser + err := row.Scan(&u.TelegramID, &u.Username, &u.FirstName, &u.Role, + &u.LinkedAdminUsername, &u.CreditBalance, &u.TrialUsed, &u.CreatedAt, &u.LastSeenAt) + if err != nil { + return nil, err + } + return &u, nil +} + +const botUserCols = `telegram_id, username, first_name, role, linked_admin_username, credit_balance, trial_used, created_at, last_seen_at` + +func (s *Store) GetBotUser(ctx context.Context, telegramID int64) (*BotUser, error) { + row := s.db.QueryRowContext(ctx, `SELECT `+botUserCols+` FROM bot_users WHERE telegram_id=$1`, telegramID) + return scanBotUser(row) +} + +func (s *Store) ListBotUsers(ctx context.Context) ([]*BotUser, error) { + rows, err := s.db.QueryContext(ctx, `SELECT `+botUserCols+` FROM bot_users ORDER BY last_seen_at DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotUser + for rows.Next() { + u, err := scanBotUser(rows) + if err != nil { + return nil, err + } + out = append(out, u) + } + return out, rows.Err() +} + +// SetBotUserRole updates role and reseller linkage. +func (s *Store) SetBotUserRole(ctx context.Context, telegramID int64, role, linkedAdmin string) error { + _, err := s.db.ExecContext(ctx, + `UPDATE bot_users SET role=$2, linked_admin_username=$3 WHERE telegram_id=$1`, + telegramID, role, linkedAdmin) + return err +} + +func (s *Store) SetBotUserTrialUsed(ctx context.Context, telegramID int64) error { + _, err := s.db.ExecContext(ctx, `UPDATE bot_users SET trial_used=true WHERE telegram_id=$1`, telegramID) + return err +} + +// AdjustCredits changes a reseller's balance atomically and writes a ledger row. +// Returns the resulting balance. Fails (rolls back) if the balance would go negative. +func (s *Store) AdjustCredits(ctx context.Context, telegramID int64, delta int, reason string, refTxn *int) (int, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + + var balance int + if err := tx.QueryRowContext(ctx, + `UPDATE bot_users SET credit_balance = credit_balance + $2 + WHERE telegram_id=$1 RETURNING credit_balance`, + telegramID, delta).Scan(&balance); err != nil { + return 0, err + } + if balance < 0 { + return 0, errInsufficientCredits + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO bot_credits_ledger (telegram_id, delta, reason, ref_transaction_id, balance_after) + VALUES ($1,$2,$3,$4,$5)`, + telegramID, delta, reason, refTxn, balance); err != nil { + return 0, err + } + if err := tx.Commit(); err != nil { + return 0, err + } + return balance, nil +} + +func (s *Store) ListLedger(ctx context.Context, telegramID int64, limit int) ([]*BotLedgerEntry, error) { + if limit <= 0 { + limit = 100 + } + rows, err := s.db.QueryContext(ctx, + `SELECT id, telegram_id, delta, reason, ref_transaction_id, balance_after, created_at + FROM bot_credits_ledger WHERE telegram_id=$1 ORDER BY id DESC LIMIT $2`, telegramID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotLedgerEntry + for rows.Next() { + var e BotLedgerEntry + if err := rows.Scan(&e.ID, &e.TelegramID, &e.Delta, &e.Reason, &e.RefTxnID, &e.BalanceAfter, &e.CreatedAt); err != nil { + return nil, err + } + out = append(out, &e) + } + return out, rows.Err() +} + +// ---------- bot_plans ---------- + +const botPlanCols = `id, name, kind, days, max_connections, limit_mbps_up, limit_mbps_down, xray_inbound_tag, xray_protocol, price_cents, credit_cost, server_id, is_active, sort_order` + +func scanBotPlan(row interface{ Scan(...interface{}) error }) (*BotPlan, error) { + var p BotPlan + err := row.Scan(&p.ID, &p.Name, &p.Kind, &p.Days, &p.MaxConnections, &p.LimitMbpsUp, &p.LimitMbpsDown, + &p.XrayInboundTag, &p.XrayProtocol, &p.PriceCents, &p.CreditCost, &p.ServerID, &p.IsActive, &p.SortOrder) + if err != nil { + return nil, err + } + return &p, nil +} + +func (s *Store) ListPlans(ctx context.Context, onlyActive bool) ([]*BotPlan, error) { + q := `SELECT ` + botPlanCols + ` FROM bot_plans` + if onlyActive { + q += ` WHERE is_active=true` + } + q += ` ORDER BY sort_order, id` + rows, err := s.db.QueryContext(ctx, q) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotPlan + for rows.Next() { + p, err := scanBotPlan(rows) + if err != nil { + return nil, err + } + out = append(out, p) + } + return out, rows.Err() +} + +func (s *Store) GetPlan(ctx context.Context, id int) (*BotPlan, error) { + row := s.db.QueryRowContext(ctx, `SELECT `+botPlanCols+` FROM bot_plans WHERE id=$1`, id) + return scanBotPlan(row) +} + +func (s *Store) UpsertPlan(ctx context.Context, p *BotPlan) error { + if p.ID == 0 { + return s.db.QueryRowContext(ctx, ` + INSERT INTO bot_plans (name, kind, days, max_connections, limit_mbps_up, limit_mbps_down, + xray_inbound_tag, xray_protocol, price_cents, credit_cost, server_id, is_active, sort_order) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) RETURNING id`, + p.Name, p.Kind, p.Days, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, + p.XrayInboundTag, p.XrayProtocol, p.PriceCents, p.CreditCost, p.ServerID, p.IsActive, p.SortOrder, + ).Scan(&p.ID) + } + _, err := s.db.ExecContext(ctx, ` + UPDATE bot_plans SET name=$2, kind=$3, days=$4, max_connections=$5, limit_mbps_up=$6, limit_mbps_down=$7, + xray_inbound_tag=$8, xray_protocol=$9, price_cents=$10, credit_cost=$11, server_id=$12, is_active=$13, sort_order=$14 + WHERE id=$1`, + p.ID, p.Name, p.Kind, p.Days, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, + p.XrayInboundTag, p.XrayProtocol, p.PriceCents, p.CreditCost, p.ServerID, p.IsActive, p.SortOrder) + return err +} + +func (s *Store) DeletePlan(ctx context.Context, id int) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM bot_plans WHERE id=$1`, id) + return err +} + +// ---------- bot_credit_packages ---------- + +const botPkgCols = `id, name, credits, price_cents, is_active, sort_order` + +func scanBotPkg(row interface{ Scan(...interface{}) error }) (*BotCreditPackage, error) { + var p BotCreditPackage + if err := row.Scan(&p.ID, &p.Name, &p.Credits, &p.PriceCents, &p.IsActive, &p.SortOrder); err != nil { + return nil, err + } + return &p, nil +} + +func (s *Store) ListCreditPackages(ctx context.Context, onlyActive bool) ([]*BotCreditPackage, error) { + q := `SELECT ` + botPkgCols + ` FROM bot_credit_packages` + if onlyActive { + q += ` WHERE is_active=true` + } + q += ` ORDER BY sort_order, id` + rows, err := s.db.QueryContext(ctx, q) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotCreditPackage + for rows.Next() { + p, err := scanBotPkg(rows) + if err != nil { + return nil, err + } + out = append(out, p) + } + return out, rows.Err() +} + +func (s *Store) GetCreditPackage(ctx context.Context, id int) (*BotCreditPackage, error) { + row := s.db.QueryRowContext(ctx, `SELECT `+botPkgCols+` FROM bot_credit_packages WHERE id=$1`, id) + return scanBotPkg(row) +} + +func (s *Store) UpsertCreditPackage(ctx context.Context, p *BotCreditPackage) error { + if p.ID == 0 { + return s.db.QueryRowContext(ctx, + `INSERT INTO bot_credit_packages (name, credits, price_cents, is_active, sort_order) + VALUES ($1,$2,$3,$4,$5) RETURNING id`, + p.Name, p.Credits, p.PriceCents, p.IsActive, p.SortOrder).Scan(&p.ID) + } + _, err := s.db.ExecContext(ctx, + `UPDATE bot_credit_packages SET name=$2, credits=$3, price_cents=$4, is_active=$5, sort_order=$6 WHERE id=$1`, + p.ID, p.Name, p.Credits, p.PriceCents, p.IsActive, p.SortOrder) + return err +} + +func (s *Store) DeleteCreditPackage(ctx context.Context, id int) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM bot_credit_packages WHERE id=$1`, id) + return err +} + +// ---------- bot_transactions ---------- + +const botTxnCols = `id, telegram_id, type, plan_id, package_id, credits, amount_cents, mp_payment_id, mp_qr_code, mp_qr_base64, status, target_username, renew_target, created_at, paid_at, expires_at` + +func scanBotTxn(row interface{ Scan(...interface{}) error }) (*BotTransaction, error) { + var t BotTransaction + err := row.Scan(&t.ID, &t.TelegramID, &t.Type, &t.PlanID, &t.PackageID, &t.Credits, &t.AmountCents, + &t.MPPaymentID, &t.MPQRCode, &t.MPQRBase64, &t.Status, &t.TargetUsername, &t.RenewTarget, + &t.CreatedAt, &t.PaidAt, &t.ExpiresAt) + if err != nil { + return nil, err + } + return &t, nil +} + +func (s *Store) CreateTransaction(ctx context.Context, t *BotTransaction) error { + return s.db.QueryRowContext(ctx, ` + INSERT INTO bot_transactions (telegram_id, type, plan_id, package_id, credits, amount_cents, + mp_payment_id, mp_qr_code, mp_qr_base64, status, target_username, renew_target, expires_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) RETURNING id, created_at`, + t.TelegramID, t.Type, t.PlanID, t.PackageID, t.Credits, t.AmountCents, + t.MPPaymentID, t.MPQRCode, t.MPQRBase64, t.Status, t.TargetUsername, t.RenewTarget, t.ExpiresAt, + ).Scan(&t.ID, &t.CreatedAt) +} + +func (s *Store) GetTransaction(ctx context.Context, id int) (*BotTransaction, error) { + row := s.db.QueryRowContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE id=$1`, id) + return scanBotTxn(row) +} + +func (s *Store) GetTransactionByMPID(ctx context.Context, mpID string) (*BotTransaction, error) { + row := s.db.QueryRowContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE mp_payment_id=$1`, mpID) + return scanBotTxn(row) +} + +func (s *Store) ListPendingTransactions(ctx context.Context) ([]*BotTransaction, error) { + rows, err := s.db.QueryContext(ctx, + `SELECT `+botTxnCols+` FROM bot_transactions WHERE status='pending' AND mp_payment_id <> '' ORDER BY id`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotTransaction + for rows.Next() { + t, err := scanBotTxn(rows) + if err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} + +func (s *Store) ListUserTransactions(ctx context.Context, telegramID int64, limit int) ([]*BotTransaction, error) { + if limit <= 0 { + limit = 50 + } + rows, err := s.db.QueryContext(ctx, + `SELECT `+botTxnCols+` FROM bot_transactions WHERE telegram_id=$1 ORDER BY id DESC LIMIT $2`, telegramID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotTransaction + for rows.Next() { + t, err := scanBotTxn(rows) + if err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} + +func (s *Store) ListTransactions(ctx context.Context, status string, limit int) ([]*BotTransaction, error) { + if limit <= 0 { + limit = 200 + } + var rows *sql.Rows + var err error + if status != "" { + rows, err = s.db.QueryContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE status=$1 ORDER BY id DESC LIMIT $2`, status, limit) + } else { + rows, err = s.db.QueryContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions ORDER BY id DESC LIMIT $1`, limit) + } + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BotTransaction + for rows.Next() { + t, err := scanBotTxn(rows) + if err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} + +// MarkTransactionApproved atomically flips a pending txn to approved. It returns +// true only for the caller that actually performed the transition, giving +// idempotent delivery even if webhook and poller race. +func (s *Store) MarkTransactionApproved(ctx context.Context, id int) (bool, error) { + res, err := s.db.ExecContext(ctx, + `UPDATE bot_transactions SET status='approved', paid_at=NOW() WHERE id=$1 AND status='pending'`, id) + if err != nil { + return false, err + } + n, _ := res.RowsAffected() + return n == 1, nil +} + +func (s *Store) SetTransactionStatus(ctx context.Context, id int, status string) error { + _, err := s.db.ExecContext(ctx, `UPDATE bot_transactions SET status=$2 WHERE id=$1`, id, status) + return err +} + +func (s *Store) SetTransactionTarget(ctx context.Context, id int, target string) error { + _, err := s.db.ExecContext(ctx, `UPDATE bot_transactions SET target_username=$2 WHERE id=$1`, id, target) + return err +} + +// ---------- bot_settings ---------- + +func (s *Store) GetSetting(ctx context.Context, key, def string) string { + var v string + err := s.db.QueryRowContext(ctx, `SELECT value FROM bot_settings WHERE key=$1`, key).Scan(&v) + if err != nil { + return def + } + return v +} + +func (s *Store) SetSetting(ctx context.Context, key, value string) error { + _, err := s.db.ExecContext(ctx, + `INSERT INTO bot_settings (key, value) VALUES ($1,$2) + ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value`, key, value) + return err +} + +func (s *Store) AllSettings(ctx context.Context) (map[string]string, error) { + rows, err := s.db.QueryContext(ctx, `SELECT key, value FROM bot_settings`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]string{} + for rows.Next() { + var k, v string + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + out[k] = v + } + return out, rows.Err() +} + +// ---------- bot_config (row) ---------- + +// botConfigRow mirrors the DB row; secrets stay encrypted here. +type botConfigRow struct { + Enabled bool + TelegramMode string + TelegramWebhookURL string + MPConfirmMode string + MPPollInterval string + PixExpirationMinutes int + TrialEnabled bool + TrialHours int + TrialMaxConnections int + TrialKind string + TrialInboundTag string + AdminTelegramIDs []int64 + Currency string + PublicHost string + XrayPublicHost string + TelegramTokenEnc []byte + TelegramWebhookSecretEnc []byte + MPAccessTokenEnc []byte + MPWebhookSecretEnc []byte +} + +func (s *Store) getBotConfigRow(ctx context.Context) (*botConfigRow, error) { + var r botConfigRow + var ids pq.Int64Array + err := s.db.QueryRowContext(ctx, ` + SELECT enabled, telegram_mode, telegram_webhook_url, mp_confirm_mode, mp_poll_interval, + pix_expiration_minutes, trial_enabled, trial_hours, trial_max_connections, trial_kind, + trial_inbound_tag, admin_telegram_ids, currency, public_host, xray_public_host, + telegram_token_enc, telegram_webhook_secret_enc, mp_access_token_enc, mp_webhook_secret_enc + FROM bot_config WHERE id=1`).Scan( + &r.Enabled, &r.TelegramMode, &r.TelegramWebhookURL, &r.MPConfirmMode, &r.MPPollInterval, + &r.PixExpirationMinutes, &r.TrialEnabled, &r.TrialHours, &r.TrialMaxConnections, &r.TrialKind, + &r.TrialInboundTag, &ids, &r.Currency, &r.PublicHost, &r.XrayPublicHost, + &r.TelegramTokenEnc, &r.TelegramWebhookSecretEnc, &r.MPAccessTokenEnc, &r.MPWebhookSecretEnc) + if err != nil { + return nil, err + } + r.AdminTelegramIDs = []int64(ids) + return &r, nil +} + +// saveBotConfigRow writes the non-secret fields plus any encrypted blobs that +// are non-nil (nil blob = keep existing secret). +func (s *Store) saveBotConfigRow(ctx context.Context, r *botConfigRow, tokEnc, tgSecEnc, mpEnc, mpSecEnc []byte) error { + set := `enabled=$1, telegram_mode=$2, telegram_webhook_url=$3, mp_confirm_mode=$4, mp_poll_interval=$5, + pix_expiration_minutes=$6, trial_enabled=$7, trial_hours=$8, trial_max_connections=$9, trial_kind=$10, + trial_inbound_tag=$11, admin_telegram_ids=$12, currency=$13, public_host=$14, xray_public_host=$15, + updated_at=NOW()` + args := []interface{}{ + r.Enabled, r.TelegramMode, r.TelegramWebhookURL, r.MPConfirmMode, r.MPPollInterval, + r.PixExpirationMinutes, r.TrialEnabled, r.TrialHours, r.TrialMaxConnections, r.TrialKind, + r.TrialInboundTag, pq.Array(r.AdminTelegramIDs), r.Currency, r.PublicHost, r.XrayPublicHost, + } + n := len(args) + if tokEnc != nil { + n++ + set += `, telegram_token_enc=$` + botItoa(n) + args = append(args, tokEnc) + } + if tgSecEnc != nil { + n++ + set += `, telegram_webhook_secret_enc=$` + botItoa(n) + args = append(args, tgSecEnc) + } + if mpEnc != nil { + n++ + set += `, mp_access_token_enc=$` + botItoa(n) + args = append(args, mpEnc) + } + if mpSecEnc != nil { + n++ + set += `, mp_webhook_secret_enc=$` + botItoa(n) + args = append(args, mpSecEnc) + } + _, err := s.db.ExecContext(ctx, `UPDATE bot_config SET `+set+` WHERE id=1`, args...) + return err +} diff --git a/bot_telegram.go b/bot_telegram.go new file mode 100644 index 0000000..f965e50 --- /dev/null +++ b/bot_telegram.go @@ -0,0 +1,232 @@ +package main + +// bot_telegram.go — minimal Telegram Bot API client built on net/http. +// No third-party dependency. + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net/http" + "strconv" + "strings" + "time" +) + +const tgAPIBase = "https://api.telegram.org/bot" + +// ---------- Wire types (subset) ---------- + +type tgUpdate struct { + UpdateID int64 `json:"update_id"` + Message *tgMessage `json:"message"` + CallbackQuery *tgCallbackQuery `json:"callback_query"` +} + +type tgMessage struct { + MessageID int64 `json:"message_id"` + From *tgUser `json:"from"` + Chat tgChat `json:"chat"` + Text string `json:"text"` +} + +type tgCallbackQuery struct { + ID string `json:"id"` + From tgUser `json:"from"` + Message *tgMessage `json:"message"` + Data string `json:"data"` +} + +type tgUser struct { + ID int64 `json:"id"` + FirstName string `json:"first_name"` + Username string `json:"username"` +} + +type tgChat struct { + ID int64 `json:"id"` +} + +type tgInlineKeyboard struct { + InlineKeyboard [][]tgInlineButton `json:"inline_keyboard"` +} + +type tgInlineButton struct { + Text string `json:"text"` + CallbackData string `json:"callback_data,omitempty"` + URL string `json:"url,omitempty"` +} + +// ---------- Client ---------- + +type tgClient struct { + token string + hc *http.Client +} + +func newTGClient(token string) *tgClient { + return &tgClient{token: token, hc: &http.Client{Timeout: 65 * time.Second}} +} + +type tgResponse struct { + OK bool `json:"ok"` + Description string `json:"description"` + Result json.RawMessage `json:"result"` +} + +func (c *tgClient) call(ctx context.Context, method string, payload interface{}) (json.RawMessage, error) { + body, err := json.Marshal(payload) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tgAPIBase+c.token+"/"+method, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + resp, err := c.hc.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + var tr tgResponse + if err := json.Unmarshal(data, &tr); err != nil { + return nil, fmt.Errorf("telegram %s: bad response: %s", method, string(data)) + } + if !tr.OK { + return nil, fmt.Errorf("telegram %s: %s", method, tr.Description) + } + return tr.Result, nil +} + +// getUpdates long-polls. offset is the next update_id to fetch. +func (c *tgClient) getUpdates(ctx context.Context, offset int64, timeoutSec int) ([]tgUpdate, error) { + payload := map[string]interface{}{ + "offset": offset, + "timeout": timeoutSec, + "allowed_updates": []string{"message", "callback_query"}, + } + raw, err := c.call(ctx, "getUpdates", payload) + if err != nil { + return nil, err + } + var ups []tgUpdate + if err := json.Unmarshal(raw, &ups); err != nil { + return nil, err + } + return ups, nil +} + +func (c *tgClient) sendMessage(ctx context.Context, chatID int64, text string, kb *tgInlineKeyboard) (int64, error) { + payload := map[string]interface{}{ + "chat_id": chatID, + "text": text, + "parse_mode": "HTML", + "disable_web_page_preview": true, + } + if kb != nil { + payload["reply_markup"] = kb + } + raw, err := c.call(ctx, "sendMessage", payload) + if err != nil { + return 0, err + } + var m tgMessage + _ = json.Unmarshal(raw, &m) + return m.MessageID, nil +} + +func (c *tgClient) editMessageText(ctx context.Context, chatID, messageID int64, text string, kb *tgInlineKeyboard) error { + payload := map[string]interface{}{ + "chat_id": chatID, + "message_id": messageID, + "text": text, + "parse_mode": "HTML", + "disable_web_page_preview": true, + } + if kb != nil { + payload["reply_markup"] = kb + } + _, err := c.call(ctx, "editMessageText", payload) + return err +} + +func (c *tgClient) answerCallback(ctx context.Context, callbackID, text string) error { + payload := map[string]interface{}{"callback_query_id": callbackID} + if text != "" { + payload["text"] = text + } + _, err := c.call(ctx, "answerCallbackQuery", payload) + return err +} + +// sendPhotoBytes uploads a photo (e.g. a PIX QR PNG) via multipart. +func (c *tgClient) sendPhotoBytes(ctx context.Context, chatID int64, photo []byte, filename, caption string, kb *tgInlineKeyboard) (int64, error) { + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + _ = w.WriteField("chat_id", strconv.FormatInt(chatID, 10)) + if caption != "" { + _ = w.WriteField("caption", caption) + _ = w.WriteField("parse_mode", "HTML") + } + if kb != nil { + kbJSON, _ := json.Marshal(kb) + _ = w.WriteField("reply_markup", string(kbJSON)) + } + fw, err := w.CreateFormFile("photo", filename) + if err != nil { + return 0, err + } + if _, err := fw.Write(photo); err != nil { + return 0, err + } + _ = w.Close() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tgAPIBase+c.token+"/sendPhoto", &buf) + if err != nil { + return 0, err + } + req.Header.Set("Content-Type", w.FormDataContentType()) + resp, err := c.hc.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + var tr tgResponse + if err := json.Unmarshal(data, &tr); err != nil || !tr.OK { + return 0, fmt.Errorf("telegram sendPhoto: %s", string(data)) + } + var m tgMessage + _ = json.Unmarshal(tr.Result, &m) + return m.MessageID, nil +} + +func (c *tgClient) deleteWebhook(ctx context.Context) error { + _, err := c.call(ctx, "deleteWebhook", map[string]interface{}{"drop_pending_updates": false}) + return err +} + +// getMe validates the token and returns the bot username. +func (c *tgClient) getMe(ctx context.Context) (string, error) { + raw, err := c.call(ctx, "getMe", map[string]interface{}{}) + if err != nil { + return "", err + } + var me tgUser + _ = json.Unmarshal(raw, &me) + return me.Username, nil +} + +// ---------- helpers ---------- + +func htmlEscape(s string) string { + s = strings.ReplaceAll(s, "&", "&") + s = strings.ReplaceAll(s, "<", "<") + s = strings.ReplaceAll(s, ">", ">") + return s +} diff --git a/btun_integration.go b/btun_integration.go new file mode 100644 index 0000000..2cd761d --- /dev/null +++ b/btun_integration.go @@ -0,0 +1,994 @@ +package main + +// This file embeds the BTUN protocol server into the panel. BTUN is the native +// DTunnel VPN transport: a client speaks a "DTUNNEL/1.1 CLIENT_HELLO" handshake +// over TCP or UDP, authenticates, is handed an IPv4 address from a private +// subnet, and then exchanges raw IPv4 packets with a TUN interface owned by +// this process. +// +// Unlike BHTTP or DNSTT, BTUN is not an SSH carrier — it moves IP packets, not +// an SSH stream. Authentication therefore cannot be delegated to handleConn, so +// it is delegated to the panel's own account database instead: the same +// username/password (or TOTP), the same expiry, reseller-owner, data-quota and +// max_connections rules that passwordCallback enforces for SSH. PAM, +// /etc/shadow and password files are deliberately unreachable from this path; +// a BTUN login is a panel login and nothing else. + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "os/exec" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/time/rate" + + "shell2/internal/btun" +) + +// BTUNConfig defines the settings for the integrated BTUN server. A nil +// *BTUNConfig in the main config disables it entirely. +type BTUNConfig struct { + // TCPListen is the TCP address for BTUN clients. Empty disables the TCP + // transport. IPv6 addresses must use bracket form, e.g. "[::]:7300". + TCPListen string `json:"tcp_listen"` + + // UDPListen is the UDP address for BTUN clients. Empty disables the UDP + // transport. At least one of TCPListen/UDPListen must be set. + UDPListen string `json:"udp_listen"` + + // SharedPorts also accepts BTUN on the ports the panel already owns: the + // HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080) + // and every TLS forwarder (normally 443). Those listeners read the first + // bytes of each connection and hand it here only on the fixed + // "DTUNNEL/1.1 CLIENT_HELLO" marker, so SSH and HTTP-injection clients on + // the same port are unaffected. + // + // This covers the TCP transport only: the panel owns no shared UDP port, so + // UDP clients still need UDPListen. A TCP client that prepends cover bytes + // is matched when that cover is an HTTP request (the panel's own HTTP + // cleanup consumes it first); other cover shapes need TCPListen, because a + // shared port cannot buffer an unbounded prefix while SSH waits behind it. + SharedPorts bool `json:"shared_ports,omitempty"` + + // TUNName is the TUN interface this server creates and owns. Default + // "btun0". It must not collide with an interface another service owns. + TUNName string `json:"tun_name,omitempty"` + + // Subnet is the private IPv4 range handed out to clients, in CIDR form. + // Default "10.77.0.0/16". It must have room for at least four addresses. + Subnet string `json:"subnet,omitempty"` + + // Gateway is the address configured on the TUN interface itself, in CIDR + // form, and is the first usable address of Subnet by convention. Empty + // derives it from Subnet (for 10.77.0.0/16 that is 10.77.0.1/16). + Gateway string `json:"gateway,omitempty"` + + // MTU is set on the TUN interface. Default 1400, which leaves headroom for + // the BTUN framing plus an outer TCP/UDP header on a 1500-byte path. + MTU int `json:"mtu,omitempty"` + + // ManageRouting lets the panel configure the interface address, MTU, + // net.ipv4.ip_forward and the NAT/forward rules for Subnet itself. Turn it + // off only when an external script (or an existing btun-routing unit) + // already owns those rules. + ManageRouting bool `json:"manage_routing,omitempty"` + + // WANInterface is the uplink used for NAT. Empty auto-detects it from the + // default IPv4 route, which is correct on a single-uplink VPS. + WANInterface string `json:"wan_interface,omitempty"` + + // HandshakeTimeout bounds the hello + authentication exchange. Empty + // defaults to "15s". + HandshakeTimeout string `json:"handshake_timeout,omitempty"` + + // IdleTimeout drops a session that sends nothing for this long. Empty + // defaults to "2m". Clients send keep-alives, so this only reaps dead peers. + IdleTimeout string `json:"idle_timeout,omitempty"` + + // MaxPacketSize limits a single BTUN frame payload in bytes. Zero uses the + // protocol default (64 KiB); the hard ceiling is 4 MiB. + MaxPacketSize int `json:"max_packet_size,omitempty"` + + // MaxCoverBytes is how much junk a TCP client may send before its + // CLIENT_HELLO, which is what lets BTUN hide behind an HTTP-looking + // preamble. Zero uses the default (64 KiB). + MaxCoverBytes int `json:"max_cover_bytes,omitempty"` + + // MaxSessions caps concurrent BTUN sessions across both transports. Zero + // uses a safe default; negative disables the cap. Per-account limits still + // come from each user's max_connections. + MaxSessions int `json:"max_sessions,omitempty"` + + // DisableConsoleLog keeps BTUN log lines out of stderr. They are still + // captured in memory and served by /api/btun/logs for the panel. + DisableConsoleLog bool `json:"disable_console_log,omitempty"` + + // LogConnections enables one log line per session start/stop. + LogConnections bool `json:"log_connections,omitempty"` + + // AutoRestartInterval controls a watchdog that periodically hard-restarts + // only the BTUN listeners and TUN device. Empty, "0s", "off" or "disabled" + // turns it off. Minimum accepted value is 1m. + AutoRestartInterval string `json:"auto_restart_interval,omitempty"` + + // AutoRestartGrace is the delay between tearing the old instance down and + // bringing a new one up during an auto restart. Empty defaults to "2s". + AutoRestartGrace string `json:"auto_restart_grace,omitempty"` +} + +const ( + defaultBTUNTCPListen = "0.0.0.0:7300" + defaultBTUNUDPListen = "0.0.0.0:7300" + defaultBTUNName = "btun0" + defaultBTUNSubnet = "10.77.0.0/16" + defaultBTUNMTU = 1400 + defaultBTUNHandshakeTimeout = 15 * time.Second + defaultBTUNIdleTimeout = 2 * time.Minute + defaultBTUNMaxSessions = 10000 + btunMaxPacketCeiling = 4 * 1024 * 1024 + btunRouteCommandTimeout = 10 * time.Second +) + +var ( + btunMu sync.Mutex + btunServer *btun.Server + btunDevice btun.PacketDevice + btunTCP net.Listener + btunUDP net.PacketConn + btunListenTCP string + btunListenUDP string + // btunSharedPorts mirrors BTUNConfig.SharedPorts for the running instance, + // so the proxy and TLS listeners can check it without reading the whole + // config on every connection. + btunSharedPorts bool + // btunRoutingApplied records the settings used to add routing rules, so the + // exact same rules can be removed on shutdown even after the config changed. + btunRoutingApplied *btunRoutingSpec + + btunAutoMu sync.Mutex + btunAutoCancel context.CancelFunc + + btunLog = log.New(os.Stderr, "btun: ", log.LstdFlags|log.Lmicroseconds) + btunLogBuf *ringLogBuffer + + // btunSessionsMu guards the per-account session registry used for + // max_connections and for forced disconnects from the panel. + btunSessionsMu sync.Mutex + btunSessions = make(map[string]map[*btunLedger]struct{}) +) + +func getBTUNLogLines() []string { return btunLogBuf.GetLines() } + +// ---------- Panel-backed authentication ---------- + +// btunPanelAuthenticator verifies a BTUN credential against the panel's own +// account database. It is intentionally the only authenticator wired into the +// BTUN server: there is no PAM, /etc/shadow or password-file path here, and +// pam_auth_enabled does not apply to BTUN. +type btunPanelAuthenticator struct{} + +func (btunPanelAuthenticator) Name() string { return "panel" } + +func (btunPanelAuthenticator) Authenticate(username, password string) error { + // Mirrors passwordCallback's panel-credential branch. Kept as a separate + // implementation because passwordCallback is bound to ssh.ConnMetadata and + // also owns the (unrelated) system-login path. + u, ok := userMgr.Get(username) + if !ok { + return errors.New("invalid username or password") + } + now := time.Now() + if u.ExpiresAt != nil && now.After(*u.ExpiresAt) { + return errors.New("account expired") + } + if sshUserQuotaBlocked(u) { + return errDataQuotaExceeded + } + if err := ownerIsActive(u.Cfg.OwnerUsername); err != nil { + return errors.New("invalid username or password") + } + u.mu.Lock() + cfg := u.Cfg + u.mu.Unlock() + if strings.TrimSpace(cfg.TOTPSecret) != "" { + if matchTOTPPassword(u, password, now) { + return nil + } + if cfg.AllowStaticPassword && cfg.Password == password { + return nil + } + return errors.New("invalid username or password") + } + if cfg.Password != password { + return errors.New("invalid username or password") + } + return nil +} + +// ---------- Panel-backed accounting ---------- + +// btunPanelAccountant admits authenticated BTUN sessions and meters their +// traffic against the same per-user counters the SSH path uses, so a user's +// bandwidth limits, data quota and connection count cover both transports. +type btunPanelAccountant struct{} + +func (btunPanelAccountant) Admit(username, remote string, closer io.Closer) (btun.Ledger, error) { + u, ok := userMgr.Get(username) + if !ok { + return nil, errors.New("account not found") + } + u.mu.Lock() + cfg := u.Cfg + // max_connections is shared with SSH: BTUN sessions and SSH connections + // count against the same allowance, so a user cannot double their limit by + // mixing transports. + active := len(u.conns) + u.btunConns + if cfg.MaxConnections > 0 && active >= cfg.MaxConnections { + u.mu.Unlock() + return nil, fmt.Errorf("connection limit reached (%d)", cfg.MaxConnections) + } + u.btunConns++ + u.ActiveConns = len(u.conns) + u.btunConns + u.mu.Unlock() + + limitUp, limitDown := cfg.LimitMbpsUp, cfg.LimitMbpsDown + if limitUp == 0 || limitDown == 0 { + defUp, defDown := getDefaultLimits() + if limitUp == 0 { + limitUp = defUp + } + if limitDown == 0 { + limitDown = defDown + } + } + ledger := &btunLedger{ + user: u, + username: username, + remote: remote, + closer: closer, + up: btunRateLimiter(limitUp), + down: btunRateLimiter(limitDown), + } + + btunSessionsMu.Lock() + if btunSessions[username] == nil { + btunSessions[username] = make(map[*btunLedger]struct{}) + } + btunSessions[username][ledger] = struct{}{} + btunSessionsMu.Unlock() + + updateUserDisplay() + return ledger, nil +} + +// btunRateLimiter builds a per-session limiter for an Mbps value. The burst is +// never smaller than one maximum-size IP packet, otherwise WaitN would reject +// a legitimate packet outright instead of pacing it. +func btunRateLimiter(mbps int) *rate.Limiter { + if mbps <= 0 { + return nil + } + bps := mbpsToBytesPerSec(mbps) + burst := int(bps) + if burst < 64*1024 { + burst = 64 * 1024 + } + return rate.NewLimiter(rate.Limit(bps), burst) +} + +// btunLedger meters one BTUN session against its panel account. +type btunLedger struct { + user *UserState + username string + remote string + closer io.Closer + up *rate.Limiter + down *rate.Limiter + once sync.Once +} + +func (l *btunLedger) Uplink(ctx context.Context, n int) error { + return l.meter(ctx, true, l.up, n) +} + +func (l *btunLedger) Downlink(ctx context.Context, n int) error { + return l.meter(ctx, false, l.down, n) +} + +// meter reserves quota for one IP packet, paces it, and commits the bytes. +// BTUN forwards whole packets, so a partial quota allowance cannot be honoured: +// the reservation is released and the session ends instead of sending a +// truncated packet. +func (l *btunLedger) meter(ctx context.Context, uplink bool, limiter *rate.Limiter, n int) error { + if l.user == nil || n <= 0 { + return nil + } + // Held for the same reason sshQuotaWriter holds it: a traffic reset must not + // interleave with a reservation. + l.user.trafficMu.RLock() + defer l.user.trafficMu.RUnlock() + + allowed, quotaLimiter, stopAfter := reserveSSHUserBytes(l.user, n) + if allowed <= 0 { + return errDataQuotaExceeded + } + if allowed < n { + finishSSHUserReservation(l.user, uplink, allowed, 0) + return errDataQuotaExceeded + } + if limiter != nil { + if err := limiter.WaitN(ctx, n); err != nil { + finishSSHUserReservation(l.user, uplink, allowed, 0) + return err + } + } + if quotaLimiter != nil { + if err := quotaLimiter.WaitN(ctx, allowed); err != nil { + finishSSHUserReservation(l.user, uplink, allowed, 0) + return err + } + } + finishSSHUserReservation(l.user, uplink, allowed, allowed) + if stopAfter { + return errDataQuotaExceeded + } + return nil +} + +func (l *btunLedger) Close() { + l.once.Do(func() { + btunSessionsMu.Lock() + if set := btunSessions[l.username]; set != nil { + delete(set, l) + if len(set) == 0 { + delete(btunSessions, l.username) + } + } + btunSessionsMu.Unlock() + + if l.user != nil { + l.user.mu.Lock() + if l.user.btunConns > 0 { + l.user.btunConns-- + } + l.user.ActiveConns = len(l.user.conns) + l.user.btunConns + l.user.mu.Unlock() + } + updateUserDisplay() + }) +} + +// btunDisconnectUser closes every BTUN session belonging to username. It is +// called from UserManager.DisconnectUser so panel actions (delete, edit, +// expire) drop BTUN sessions the same way they drop SSH connections. +func btunDisconnectUser(username string) int { + btunSessionsMu.Lock() + ledgers := make([]*btunLedger, 0, len(btunSessions[username])) + for ledger := range btunSessions[username] { + ledgers = append(ledgers, ledger) + } + btunSessionsMu.Unlock() + for _, ledger := range ledgers { + if ledger.closer != nil { + _ = ledger.closer.Close() + } + } + return len(ledgers) +} + +// btunDisconnectAll closes every tracked BTUN session. +func btunDisconnectAll() int { + btunSessionsMu.Lock() + ledgers := make([]*btunLedger, 0, len(btunSessions)) + for _, set := range btunSessions { + for ledger := range set { + ledgers = append(ledgers, ledger) + } + } + btunSessionsMu.Unlock() + for _, ledger := range ledgers { + if ledger.closer != nil { + _ = ledger.closer.Close() + } + } + return len(ledgers) +} + +// ---------- Lifecycle ---------- + +// stopBTUN tears down the BTUN listeners, TUN device, routing rules and the +// optional auto-restart watchdog. It is a no-op if BTUN is not running. +func stopBTUN() { + stopBTUNAutoRestart() + stopBTUNInstance() +} + +// stopBTUNInstance closes only the running instance. The auto-restart watchdog +// uses this so it can cycle BTUN without disabling itself. +func stopBTUNInstance() { + btunMu.Lock() + server := btunServer + device := btunDevice + tcpListener := btunTCP + udpConn := btunUDP + routing := btunRoutingApplied + btunServer = nil + btunDevice = nil + btunTCP = nil + btunUDP = nil + btunListenTCP = "" + btunListenUDP = "" + btunSharedPorts = false + btunRoutingApplied = nil + btunMu.Unlock() + + if tcpListener != nil { + _ = tcpListener.Close() + } + if udpConn != nil { + _ = udpConn.Close() + } + if server != nil { + // Server.Close also closes the TUN device it was given. + if err := server.Close(); err != nil { + btunLog.Printf("shutdown: %v", err) + } + server.Wait() + } else if device != nil { + _ = device.Close() + } + if routing != nil { + removeBTUNRouting(*routing) + } +} + +func stopBTUNAutoRestart() { + btunAutoMu.Lock() + defer btunAutoMu.Unlock() + if btunAutoCancel != nil { + btunAutoCancel() + btunAutoCancel = nil + } +} + +func btunRunning() bool { + btunMu.Lock() + defer btunMu.Unlock() + return btunServer != nil +} + +// btunListenList reports the addresses currently bound, for the panel. +func btunListenList() string { + btunMu.Lock() + defer btunMu.Unlock() + parts := make([]string, 0, 3) + if btunListenTCP != "" { + parts = append(parts, "tcp "+btunListenTCP) + } + if btunListenUDP != "" { + parts = append(parts, "udp "+btunListenUDP) + } + if btunSharedPorts { + parts = append(parts, "shared proxy/TLS ports") + } + return strings.Join(parts, ", ") +} + +// btunShareEnabled reports whether a running BTUN server wants the shared proxy +// and TLS ports. +func btunShareEnabled() bool { + btunMu.Lock() + defer btunMu.Unlock() + return btunServer != nil && btunSharedPorts +} + +// btunConfiguredListen describes the addresses a config asks for, used in +// status reports when the server failed to bind them. +func btunConfiguredListen(cfg *BTUNConfig) string { + if cfg == nil { + return "" + } + parts := make([]string, 0, 3) + if addr := strings.TrimSpace(cfg.TCPListen); addr != "" { + parts = append(parts, "tcp "+addr) + } + if addr := strings.TrimSpace(cfg.UDPListen); addr != "" { + parts = append(parts, "udp "+addr) + } + if cfg.SharedPorts { + parts = append(parts, "shared proxy/TLS ports") + } + return strings.Join(parts, ", ") +} + +func btunEnabledInCurrentConfig() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.BTUN != nil +} + +// startBTUN starts the integrated BTUN server if cfg is non-nil. Startup errors +// are returned so the admin panel can report them, but they never crash the +// panel. +func startBTUN(cfg *BTUNConfig) error { + if cfg == nil { + return nil + } + stopBTUNAutoRestart() + if err := startBTUNInstance(cfg); err != nil { + return err + } + startBTUNAutoRestart(cfg) + return nil +} + +func startBTUNInstance(cfg *BTUNConfig) error { + if cfg == nil { + return nil + } + if btunLogBuf == nil { + btunLogBuf = newRingLogBuffer(200) + } + if cfg.DisableConsoleLog { + btunLog.SetOutput(btunLogBuf) + } else { + btunLog.SetOutput(io.MultiWriter(btunLogBuf, os.Stderr)) + } + + normalizeBTUNConfig(cfg) + if cfg.TCPListen == "" && cfg.UDPListen == "" && !cfg.SharedPorts { + msg := errors.New("btun: needs tcp_listen, udp_listen or shared_ports") + btunLog.Print(msg.Error()) + return msg + } + + // Release the previous instance first: the TUN interface name and the + // listen addresses cannot be held twice. + stopBTUNInstance() + + device, err := btun.OpenTUN(cfg.TUNName) + if err != nil { + msg := fmt.Errorf("btun: open TUN %s: %w", cfg.TUNName, err) + btunLog.Print(msg.Error()) + return msg + } + + maxSessions := cfg.MaxSessions + if maxSessions == 0 { + maxSessions = defaultBTUNMaxSessions + } else if maxSessions < 0 { + maxSessions = 0 // unlimited + } + + server, err := btun.NewServer(btun.Config{ + Subnet: cfg.Subnet, + Authenticator: btunPanelAuthenticator{}, + Accountant: btunPanelAccountant{}, + Logger: btunLog, + HandshakeTimeout: btunDurationOrDefault(cfg.HandshakeTimeout, defaultBTUNHandshakeTimeout, "handshake_timeout"), + IdleTimeout: btunDurationOrDefault(cfg.IdleTimeout, defaultBTUNIdleTimeout, "idle_timeout"), + MaxPacketSize: cfg.MaxPacketSize, + MaxCoverBytes: cfg.MaxCoverBytes, + MaxSessions: maxSessions, + LogConnections: cfg.LogConnections, + }, device) + if err != nil { + _ = device.Close() + msg := fmt.Errorf("btun: %w", err) + btunLog.Print(msg.Error()) + return msg + } + + var tcpListener net.Listener + if cfg.TCPListen != "" { + tcpListener, err = net.Listen("tcp", cfg.TCPListen) + if err != nil { + _ = server.Close() + msg := fmt.Errorf("btun: listen TCP %s: %w", cfg.TCPListen, err) + btunLog.Print(msg.Error()) + return msg + } + } + var udpConn net.PacketConn + if cfg.UDPListen != "" { + udpConn, err = net.ListenPacket("udp", cfg.UDPListen) + if err != nil { + if tcpListener != nil { + _ = tcpListener.Close() + } + _ = server.Close() + msg := fmt.Errorf("btun: listen UDP %s: %w", cfg.UDPListen, err) + btunLog.Print(msg.Error()) + return msg + } + } + + var routing *btunRoutingSpec + if cfg.ManageRouting { + spec, routeErr := applyBTUNRouting(cfg, device.Name()) + if routeErr != nil { + // Routing is a host-configuration concern: the tunnel itself is up, + // so keep serving and surface the problem instead of refusing to + // start. Without NAT clients reach the server but not the internet. + btunLog.Printf("routing not fully applied: %v", routeErr) + } + routing = &spec + } + + btunMu.Lock() + btunServer = server + btunDevice = device + btunTCP = tcpListener + btunUDP = udpConn + btunListenTCP = cfg.TCPListen + btunListenUDP = cfg.UDPListen + btunSharedPorts = cfg.SharedPorts + btunRoutingApplied = routing + btunMu.Unlock() + + btunLog.Printf("starting: tun=%s subnet=%s gateway=%s mtu=%d tcp=%q udp=%q shared_ports=%v auth=panel manage_routing=%v max_sessions=%d log_connections=%v", + device.Name(), cfg.Subnet, cfg.Gateway, cfg.MTU, cfg.TCPListen, cfg.UDPListen, + cfg.SharedPorts, cfg.ManageRouting, maxSessions, cfg.LogConnections) + + if tcpListener != nil { + go func() { + defer btunRecover("ServeTCP") + if err := server.ServeTCP(tcpListener); err != nil && !isListenerClosed(err) { + btunLog.Printf("TCP listener stopped: %v", err) + } + }() + } + if udpConn != nil { + go func() { + defer btunRecover("ServeUDP") + if err := server.ServeUDP(udpConn); err != nil && !isListenerClosed(err) { + btunLog.Printf("UDP listener stopped: %v", err) + } + }() + } + return nil +} + +func btunRecover(where string) { + if r := recover(); r != nil { + btunLog.Printf("recovered panic in %s: %v", where, r) + } +} + +func startBTUNAutoRestart(cfg *BTUNConfig) { + interval := btunAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := btunAutoRestartGrace(cfg) + cfgCopy := *cfg + ctx, cancel := context.WithCancel(context.Background()) + + btunAutoMu.Lock() + if btunAutoCancel != nil { + btunAutoCancel() + } + btunAutoCancel = cancel + btunAutoMu.Unlock() + + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + btunLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace) + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + btunLog.Print("auto restart: stopping listeners, sessions and TUN device") + stopBTUNInstance() + if !sleepOrContextDone(ctx, grace) { + return + } + for attempt := 1; ; attempt++ { + if err := startBTUNInstance(&cfgCopy); err != nil { + btunLog.Printf("auto restart: start attempt %d failed: %v", attempt, err) + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + continue + } + btunLog.Print("auto restart: server restarted") + break + } + } + } + }() +} + +func btunAutoRestartInterval(cfg *BTUNConfig) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.AutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + btunLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err) + return 0 + } + if d < time.Minute { + btunLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw) + return 0 + } + return d +} + +func btunAutoRestartGrace(cfg *BTUNConfig) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace)) + if err != nil || d < 0 { + btunLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace) + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +func btunDurationOrDefault(raw string, fallback time.Duration, field string) time.Duration { + raw = strings.TrimSpace(raw) + if raw == "" { + return fallback + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + btunLog.Printf("invalid %s %q; using default %s", field, raw, fallback) + return fallback + } + return d +} + +// normalizeBTUNConfig fills in defaults and derives the gateway address. It +// mutates cfg so the value persisted by the admin API matches what runs. +func normalizeBTUNConfig(cfg *BTUNConfig) { + cfg.TCPListen = strings.TrimSpace(cfg.TCPListen) + cfg.UDPListen = strings.TrimSpace(cfg.UDPListen) + cfg.TUNName = strings.TrimSpace(cfg.TUNName) + if cfg.TUNName == "" { + cfg.TUNName = defaultBTUNName + } + cfg.Subnet = strings.TrimSpace(cfg.Subnet) + if cfg.Subnet == "" { + cfg.Subnet = defaultBTUNSubnet + } + cfg.Gateway = strings.TrimSpace(cfg.Gateway) + if cfg.Gateway == "" { + if derived, err := btunGatewayForSubnet(cfg.Subnet); err == nil { + cfg.Gateway = derived + } + } + if cfg.MTU <= 0 { + cfg.MTU = defaultBTUNMTU + } + if cfg.MaxPacketSize > btunMaxPacketCeiling { + btunLog.Printf("max_packet_size %d exceeds the %d ceiling; clamping", + cfg.MaxPacketSize, btunMaxPacketCeiling) + cfg.MaxPacketSize = btunMaxPacketCeiling + } + cfg.WANInterface = strings.TrimSpace(cfg.WANInterface) +} + +// btunGatewayForSubnet returns the first usable address of subnet in CIDR form, +// which is the address the TUN interface takes. For 10.77.0.0/16 that is +// 10.77.0.1/16. +func btunGatewayForSubnet(subnet string) (string, error) { + ip, network, err := net.ParseCIDR(subnet) + if err != nil { + return "", err + } + if ip.To4() == nil { + return "", errors.New("BTUN subnet must be IPv4") + } + ones, bits := network.Mask.Size() + if bits != 32 || ones > 30 { + return "", errors.New("BTUN subnet must contain at least four IPv4 addresses") + } + base := network.IP.To4() + gateway := net.IPv4(base[0], base[1], base[2], base[3]).To4() + gateway[3] |= 1 + return fmt.Sprintf("%s/%d", gateway.String(), ones), nil +} + +// ---------- Host routing ---------- + +// btunRoutingSpec records exactly which rules were installed, so the same ones +// can be removed later even if the configuration changed in between. +type btunRoutingSpec struct { + TUNName string + Subnet string + Gateway string + MTU int + WAN string +} + +// applyBTUNRouting configures the TUN interface and the NAT/forward rules that +// let BTUN clients reach the internet. It mirrors deploy/btun/btun-routing from +// the standalone deployment, but runs in-process so the panel owns the state. +func applyBTUNRouting(cfg *BTUNConfig, tunName string) (btunRoutingSpec, error) { + spec := btunRoutingSpec{ + TUNName: tunName, + Subnet: cfg.Subnet, + Gateway: cfg.Gateway, + MTU: cfg.MTU, + WAN: cfg.WANInterface, + } + if spec.WAN == "" { + detected, err := detectDefaultWANInterface() + if err != nil { + return spec, fmt.Errorf("detect WAN interface: %w (set wan_interface explicitly)", err) + } + spec.WAN = detected + btunLog.Printf("routing: detected WAN interface %s", detected) + } + + var problems []string + run := func(name string, args ...string) { + if out, err := runBTUNCommand(name, args...); err != nil { + problems = append(problems, fmt.Sprintf("%s %s: %v%s", name, strings.Join(args, " "), err, out)) + } + } + + if spec.Gateway != "" { + run("ip", "address", "replace", spec.Gateway, "dev", spec.TUNName) + } + run("ip", "link", "set", "dev", spec.TUNName, "mtu", strconv.Itoa(spec.MTU), "up") + // Only write the sysctl when forwarding is actually off. On most hosts it + // is already on, and the write is denied in restricted environments + // (containers, hardened kernels) where forwarding nonetheless works, which + // would otherwise report a failure for something already correct. + if !ipForwardingEnabled() { + run("sysctl", "-w", "net.ipv4.ip_forward=1") + } + + // Each rule is added only when an identical one is not already present, so + // repeated restarts do not stack duplicates in the tables. + ensure := func(check, add []string) { + if _, err := runBTUNCommand("iptables", check...); err == nil { + return + } + if out, err := runBTUNCommand("iptables", add...); err != nil { + problems = append(problems, fmt.Sprintf("iptables %s: %v%s", strings.Join(add, " "), err, out)) + } + } + ensure( + []string{"-t", "nat", "-C", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"}, + []string{"-t", "nat", "-A", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"}, + ) + ensure( + []string{"-C", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"}, + []string{"-A", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"}, + ) + ensure( + []string{"-C", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}, + []string{"-A", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}, + ) + + if len(problems) > 0 { + return spec, errors.New(strings.Join(problems, "; ")) + } + btunLog.Printf("routing: %s %s up, NAT via %s", spec.TUNName, spec.Gateway, spec.WAN) + return spec, nil +} + +// removeBTUNRouting deletes the rules applyBTUNRouting installed. Failures are +// logged and ignored: the rules may already be gone, or the interface may have +// disappeared with the TUN device. +func removeBTUNRouting(spec btunRoutingSpec) { + if spec.WAN == "" || spec.TUNName == "" { + return + } + deletes := [][]string{ + {"-t", "nat", "-D", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"}, + {"-D", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"}, + {"-D", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}, + } + for _, args := range deletes { + if _, err := runBTUNCommand("iptables", args...); err != nil { + btunLog.Printf("routing cleanup: iptables %s: %v", strings.Join(args, " "), err) + } + } +} + +// ipForwardingEnabled reports whether the kernel already forwards IPv4. A read +// error is treated as "not enabled" so the caller still attempts the write. +func ipForwardingEnabled() bool { + data, err := os.ReadFile("/proc/sys/net/ipv4/ip_forward") + if err != nil { + return false + } + return strings.TrimSpace(string(data)) == "1" +} + +// detectDefaultWANInterface reads the uplink from the default IPv4 route, the +// same way the standalone btun-routing script does. +func detectDefaultWANInterface() (string, error) { + out, err := runBTUNCommand("ip", "-4", "route", "show", "default") + if err != nil { + return "", err + } + for _, line := range strings.Split(out, "\n") { + fields := strings.Fields(line) + for index := 0; index+1 < len(fields); index++ { + if fields[index] == "dev" { + return fields[index+1], nil + } + } + } + return "", errors.New("no default IPv4 route") +} + +// runBTUNCommand runs a short host command with a timeout and returns its +// combined output. The output is included in error strings so a failing +// iptables rule is diagnosable from the panel. +func runBTUNCommand(name string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), btunRouteCommandTimeout) + defer cancel() + var output bytes.Buffer + command := exec.CommandContext(ctx, name, args...) + command.Stdout = &output + command.Stderr = &output + err := command.Run() + text := strings.TrimSpace(output.String()) + if text != "" { + text = ": " + text + } + return text, err +} + +// ---------- Stats ---------- + +// BTUNStatsSnapshot is what /api/btun returns. +type BTUNStatsSnapshot struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Listen string `json:"listen,omitempty"` + TUNName string `json:"tunName,omitempty"` + Subnet string `json:"subnet,omitempty"` + btun.StatsSnapshot +} + +// GetBTUNStatsSnapshot returns the current BTUN counters. It is safe for +// concurrent use and always returns a copy. +func GetBTUNStatsSnapshot() BTUNStatsSnapshot { + snapshot := BTUNStatsSnapshot{ + Enabled: btunEnabledInCurrentConfig(), + Running: btunRunning(), + Listen: btunListenList(), + } + btunMu.Lock() + server := btunServer + device := btunDevice + btunMu.Unlock() + if device != nil { + snapshot.TUNName = device.Name() + } + if server != nil { + snapshot.StatsSnapshot = server.Stats() + } + globalCfgMu.RLock() + if globalCfg != nil && globalCfg.BTUN != nil { + snapshot.Subnet = globalCfg.BTUN.Subnet + } + globalCfgMu.RUnlock() + return snapshot +} diff --git a/btun_tun_linux_test.go b/btun_tun_linux_test.go new file mode 100644 index 0000000..3d84e4a --- /dev/null +++ b/btun_tun_linux_test.go @@ -0,0 +1,184 @@ +//go:build linux + +package main + +// These tests exercise the parts of BTUN that only exist on Linux and need real +// privileges: creating the TUN interface, and installing and removing the +// NAT/forward rules that let clients reach the internet. Nothing else in the +// suite can reach that code, so without these it ships unexecuted. +// +// They are opt-in because they need NET_ADMIN and /dev/net/tun. Run them with: +// +// docker run --rm --cap-add NET_ADMIN --device /dev/net/tun \ +// -v "$PWD:/src" dragoncore-build tun + +import ( + "os" + "os/exec" + "strings" + "testing" + "time" + + "shell2/internal/btun" +) + +// requireTUN skips unless the environment can actually create a TUN device. +func requireTUN(t *testing.T) { + t.Helper() + if os.Getenv("BTUN_TUN_TESTS") == "" { + t.Skip("set BTUN_TUN_TESTS=1 and grant NET_ADMIN + /dev/net/tun to run this") + } + if _, err := os.Stat("/dev/net/tun"); err != nil { + t.Skipf("/dev/net/tun is unavailable: %v", err) + } +} + +// OpenTUN is the call that fails on a container without /dev/net/tun and is the +// single most common reason BTUN does not start. This checks that it really +// creates the interface it names, and really releases it on Close. +func TestBTUNOpenTUNCreatesAndReleasesTheInterface(t *testing.T) { + requireTUN(t) + + const name = "btuntest0" + device, err := btun.OpenTUN(name) + if err != nil { + t.Fatalf("OpenTUN(%q): %v", name, err) + } + if device.Name() != name { + t.Fatalf("device name = %q, want %q", device.Name(), name) + } + if !interfaceExists(t, name) { + t.Fatalf("interface %s was not created in the kernel", name) + } + + if err := device.Close(); err != nil { + t.Fatalf("close: %v", err) + } + // The kernel removes the interface once the last handle is gone, which may + // take a moment. + deadline := time.Now().Add(5 * time.Second) + for interfaceExists(t, name) { + if time.Now().After(deadline) { + t.Fatalf("interface %s survived the device being closed", name) + } + time.Sleep(50 * time.Millisecond) + } +} + +// An interface name the kernel cannot accept has to fail cleanly rather than +// leaving a half-open device behind. +func TestBTUNOpenTUNRejectsInvalidNames(t *testing.T) { + requireTUN(t) + + for _, name := range []string{"", "this-name-is-far-too-long"} { + if device, err := btun.OpenTUN(name); err == nil { + _ = device.Close() + t.Fatalf("OpenTUN(%q) succeeded, want an error", name) + } + } +} + +// The managed-routing path configures the interface and installs NAT. This runs +// it for real and then checks the rules it claims to have added are present, +// and that removing them leaves the tables as they were. +func TestBTUNManagedRoutingInstallsAndRemovesItsRules(t *testing.T) { + requireTUN(t) + if _, err := exec.LookPath("iptables"); err != nil { + t.Skip("iptables is not installed") + } + + const name = "btuntest1" + const subnet = "10.79.0.0/24" + device, err := btun.OpenTUN(name) + if err != nil { + t.Fatalf("OpenTUN: %v", err) + } + defer device.Close() + + cfg := &BTUNConfig{ + TCPListen: "127.0.0.1:0", + Subnet: subnet, + TUNName: name, + MTU: 1400, + ManageRouting: true, + WANInterface: "eth0", + } + normalizeBTUNConfig(cfg) + if cfg.Gateway != "10.79.0.1/24" { + t.Fatalf("derived gateway = %q, want 10.79.0.1/24", cfg.Gateway) + } + + spec, err := applyBTUNRouting(cfg, device.Name()) + if err != nil { + t.Fatalf("applyBTUNRouting: %v", err) + } + t.Cleanup(func() { removeBTUNRouting(spec) }) + + if !interfaceHasAddress(t, name, "10.79.0.1") { + t.Fatalf("gateway address was not configured on %s", name) + } + if !natRuleExists(t, subnet) { + t.Fatalf("MASQUERADE rule for %s was not installed", subnet) + } + if got := readSysctl(t, "net.ipv4.ip_forward"); got != "1" { + t.Fatalf("net.ipv4.ip_forward = %q, want 1", got) + } + + // Re-applying must not stack duplicates, which is what would happen on + // every panel restart if the rules were added unconditionally. + if _, err := applyBTUNRouting(cfg, device.Name()); err != nil { + t.Fatalf("second applyBTUNRouting: %v", err) + } + if count := natRuleCount(t, subnet); count != 1 { + t.Fatalf("MASQUERADE rule appears %d times after re-applying, want 1", count) + } + + removeBTUNRouting(spec) + if natRuleExists(t, subnet) { + t.Fatalf("MASQUERADE rule for %s survived removal", subnet) + } +} + +func interfaceExists(t *testing.T, name string) bool { + t.Helper() + return exec.Command("ip", "link", "show", name).Run() == nil +} + +func interfaceHasAddress(t *testing.T, name, address string) bool { + t.Helper() + out, err := exec.Command("ip", "-4", "addr", "show", "dev", name).CombinedOutput() + if err != nil { + t.Fatalf("ip addr show %s: %v (%s)", name, err, out) + } + return strings.Contains(string(out), address) +} + +func natRuleCount(t *testing.T, subnet string) int { + t.Helper() + out, err := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput() + if err != nil { + t.Fatalf("iptables -S POSTROUTING: %v (%s)", err, out) + } + count := 0 + for _, line := range strings.Split(string(out), "\n") { + if strings.Contains(line, subnet) && strings.Contains(line, "MASQUERADE") { + count++ + } + } + return count +} + +func natRuleExists(t *testing.T, subnet string) bool { + t.Helper() + return natRuleCount(t, subnet) > 0 +} + +func readSysctl(t *testing.T, key string) string { + t.Helper() + path := "/proc/sys/" + strings.ReplaceAll(key, ".", "/") + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return strings.TrimSpace(string(data)) +} diff --git a/check_api.go b/check_api.go new file mode 100644 index 0000000..6881539 --- /dev/null +++ b/check_api.go @@ -0,0 +1,122 @@ +package main + +import ( + "database/sql" + "encoding/json" + "net/http" + "time" +) + +// CheckResponse is returned by the public /check endpoint. +type CheckResponse struct { + Username string `json:"username"` + CountConnections int `json:"count_connections"` + ExpirationDate string `json:"expiration_date"` + ExpirationDays int `json:"expiration_days"` + LimitConnections int `json:"limit_connections"` +} + +// handleCheck is the public user-check API. No authentication required. +// Accepts ?user= or ?uuid= (or both; user takes priority). +// Returns JSON matching CheckResponse. +func handleCheck(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") + w.Header().Set("Content-Type", "application/json") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + q := r.URL.Query() + username := q.Get("user") + uuid := q.Get("uuid") + + if username == "" && uuid == "" { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"user or uuid parameter required"}`)) + return + } + + if username != "" { + checkSSHUser(w, username) + return + } + checkXrayUUID(w, r, uuid) +} + +func checkSSHUser(w http.ResponseWriter, username string) { + u, ok := userMgr.Get(username) + if !ok { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"user not found"}`)) + return + } + + u.mu.Lock() + activeConns := len(u.conns) + u.btunConns + u.ActiveConns = activeConns + maxConns := u.Cfg.MaxConnections + expiresAt := u.ExpiresAt + u.mu.Unlock() + + resp := CheckResponse{ + Username: username, + CountConnections: activeConns, + LimitConnections: maxConns, + } + fillExpiry(&resp, expiresAt) + _ = json.NewEncoder(w).Encode(resp) +} + +func checkXrayUUID(w http.ResponseWriter, r *http.Request, uuid string) { + if statsStore == nil { + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"database not configured"}`)) + return + } + + meta, err := statsStore.GetXrayClientMeta(r.Context(), uuid) + if err == sql.ErrNoRows { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"uuid not found"}`)) + return + } + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":"database error"}`)) + return + } + + displayName := meta.Name + if displayName == "" { + displayName = meta.UUID + } + + resp := CheckResponse{ + Username: displayName, + CountConnections: 0, + LimitConnections: meta.MaxConns, + } + fillExpiry(&resp, meta.ExpiresAt) + _ = json.NewEncoder(w).Encode(resp) +} + +func fillExpiry(resp *CheckResponse, expiresAt *time.Time) { + if expiresAt == nil { + resp.ExpirationDate = "Unlimited" + resp.ExpirationDays = -1 + return + } + resp.ExpirationDate = expiresAt.Local().Format("02/01/2006") + days := int(time.Until(*expiresAt).Hours() / 24) + if days < 0 { + days = 0 + } + resp.ExpirationDays = days +} diff --git a/cli_auth_test.go b/cli_auth_test.go new file mode 100644 index 0000000..002087c --- /dev/null +++ b/cli_auth_test.go @@ -0,0 +1,40 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCLIAdminBearerToken(t *testing.T) { + secret := strings.Repeat("a", 48) + t.Setenv("ADMIN_TOKEN", secret) + h := saSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if sessionFromCtx(r.Context()).Role != RoleSuperAdmin { + t.Fatal("bearer token did not receive admin role") + } + w.WriteHeader(http.StatusNoContent) + })) + for _, tc := range []struct { + name, header string + want int + }{ + {"valid", "Bearer " + secret, http.StatusNoContent}, + {"wrong", "Bearer " + strings.Repeat("b", 48), http.StatusUnauthorized}, + {"short", "Bearer a", http.StatusUnauthorized}, + {"empty", "", http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/users", nil) + if tc.header != "" { + req.Header.Set("Authorization", tc.header) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != tc.want { + t.Fatalf("got status %d, want %d", w.Code, tc.want) + } + }) + } +} diff --git a/config_safety.go b/config_safety.go new file mode 100644 index 0000000..cfa9a80 --- /dev/null +++ b/config_safety.go @@ -0,0 +1,647 @@ +package main + +import ( + "fmt" + "log" + "net" + "strconv" + "strings" + "time" +) + +const ( + defaultMainListen = "0.0.0.0:80" + defaultExtraListen = "0.0.0.0:8080" + defaultLocalSSHListen = "127.0.0.1:2222" + defaultDNSTTListen = "0.0.0.0:5300" + defaultUDPGWListen = "0.0.0.0:7400" +) + +// normalizeDurationField validates one optional duration setting in place. An +// invalid value is cleared so the service falls back to its own default rather +// than starting with a nonsense timeout. +func normalizeDurationField(value *string, label string, minimum, maximum time.Duration, warn func(string, ...interface{})) { + *value = strings.TrimSpace(*value) + if *value == "" { + return + } + d, err := time.ParseDuration(*value) + if err != nil || d <= 0 { + warn("%s %q is invalid; using the service default", label, *value) + *value = "" + return + } + if minimum > 0 && d < minimum { + warn("%s %q is below the minimum %s; clamping", label, *value, minimum) + *value = minimum.String() + return + } + if maximum > 0 && d > maximum { + warn("%s %q is above the maximum %s; clamping", label, *value, maximum) + *value = maximum.String() + } +} + +// normalizeAutoRestartFields applies the shared auto-restart rules used by +// every embedded service: an interval below 1m disables the watchdog, and the +// grace delay is capped at 1m. +func normalizeAutoRestartFields(interval, grace *string, label string, warn func(string, ...interface{})) { + *interval = strings.TrimSpace(*interval) + if *interval != "" && *interval != "0" && *interval != "0s" && + !strings.EqualFold(*interval, "off") && !strings.EqualFold(*interval, "disabled") { + if d, err := time.ParseDuration(*interval); err != nil { + warn("%s auto restart interval %q is invalid; disabling auto restart", label, *interval) + *interval = "" + } else if d < time.Minute { + warn("%s auto restart interval %q is below minimum 1m; disabling auto restart", label, *interval) + *interval = "" + } + } + *grace = strings.TrimSpace(*grace) + if *grace != "" { + if d, err := time.ParseDuration(*grace); err != nil || d < 0 { + warn("%s auto restart grace %q is invalid; using default 2s", label, *grace) + *grace = "" + } else if d > time.Minute { + warn("%s auto restart grace %q is above 1m; clamping to 1m", label, *grace) + *grace = "1m" + } + } +} + +func normalizeRuntimePorts(cfg *Config) []string { + var warnings []string + warn := func(format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + warnings = append(warnings, msg) + log.Printf("config safety: %s", msg) + } + + cfg.Listen = strings.TrimSpace(cfg.Listen) + if cfg.Listen == "" { + cfg.Listen = defaultMainListen + } + if err := tcpAddrAvailableForPool(cfg.Listen, publicPool); err != nil { + old := cfg.Listen + cfg.Listen = defaultMainListen + warn("main listener %s is unavailable (%v); using default %s", old, err, cfg.Listen) + if err2 := tcpAddrAvailableForPool(cfg.Listen, publicPool); err2 != nil { + warn("default main listener %s is also unavailable: %v", cfg.Listen, err2) + } + } + + seen := map[string]bool{cfg.Listen: true} + extra := make([]string, 0, len(cfg.ExtraListen)) + for _, addr := range cfg.ExtraListen { + addr = strings.TrimSpace(addr) + if addr == "" || seen[addr] { + continue + } + if err := tcpAddrAvailableForPool(addr, publicPool); err != nil { + warn("extra listener %s is unavailable (%v)", addr, err) + fallback := defaultExtraListen + if !seen[fallback] { + if err2 := tcpAddrAvailableForPool(fallback, publicPool); err2 == nil { + extra = append(extra, fallback) + seen[fallback] = true + warn("extra listener fell back to default %s", fallback) + } else { + warn("default extra listener %s is also unavailable: %v", fallback, err2) + } + } + continue + } + extra = append(extra, addr) + seen[addr] = true + } + cfg.ExtraListen = extra + + oldLocalSSHListen := strings.TrimSpace(cfg.LocalSSHListen) + normalizedLocalSSHListen, localSSHErr := normalizeLocalSSHListen(oldLocalSSHListen) + cfg.LocalSSHListen = normalizedLocalSSHListen + if localSSHErr != nil { + warn("internal SSH listener %q is invalid (%v); using safe default %s", oldLocalSSHListen, localSSHErr, cfg.LocalSSHListen) + } + if err := tcpAddrAvailableForPool(cfg.LocalSSHListen, localPool); err != nil { + old := cfg.LocalSSHListen + cfg.LocalSSHListen = defaultLocalSSHListen + if old != defaultLocalSSHListen { + warn("internal SSH listener %s is unavailable (%v); using default %s", old, err, cfg.LocalSSHListen) + } + if err2 := tcpAddrAvailableForPool(cfg.LocalSSHListen, localPool); err2 != nil { + warn("default internal SSH listener %s is unavailable: %v", cfg.LocalSSHListen, err2) + } + } + + cfg.ProxyAutoRestartInterval = strings.TrimSpace(cfg.ProxyAutoRestartInterval) + if cfg.ProxyAutoRestartInterval != "" && cfg.ProxyAutoRestartInterval != "0" && cfg.ProxyAutoRestartInterval != "0s" && !strings.EqualFold(cfg.ProxyAutoRestartInterval, "off") && !strings.EqualFold(cfg.ProxyAutoRestartInterval, "disabled") { + if d, err := time.ParseDuration(cfg.ProxyAutoRestartInterval); err != nil { + warn("proxy auto restart interval %q is invalid; disabling auto restart", cfg.ProxyAutoRestartInterval) + cfg.ProxyAutoRestartInterval = "" + } else if d < time.Minute { + warn("proxy auto restart interval %q is below 1m; disabling auto restart", cfg.ProxyAutoRestartInterval) + cfg.ProxyAutoRestartInterval = "" + } + } + cfg.ProxyAutoRestartGrace = strings.TrimSpace(cfg.ProxyAutoRestartGrace) + if cfg.ProxyAutoRestartGrace != "" { + if d, err := time.ParseDuration(cfg.ProxyAutoRestartGrace); err != nil || d < 0 { + warn("proxy auto restart grace %q is invalid; using default 2s", cfg.ProxyAutoRestartGrace) + cfg.ProxyAutoRestartGrace = "" + } else if d > time.Minute { + warn("proxy auto restart grace %q is above 1m; clamping to 1m", cfg.ProxyAutoRestartGrace) + cfg.ProxyAutoRestartGrace = "1m" + } + } + + if cfg.DNSTT != nil { + cfg.DNSTT.FakeDNSDomain = strings.TrimSpace(cfg.DNSTT.FakeDNSDomain) + if cfg.DNSTT.FakeDNSEnabled { + if cfg.DNSTT.FakeDNSDomain == "" { + cfg.DNSTT.FakeDNSDomain = "t.local.lan" + } + // Automatically add the local/fake test zone to the accepted DNSTT + // domains so the tunnel handler can decode traffic for it. + cfg.DNSTT.Domains = append(cfg.DNSTT.Domains, cfg.DNSTT.FakeDNSDomain) + } + cfg.DNSTT.Domains = normalizeDNSTTDomainList(cfg.DNSTT.Domain, cfg.DNSTT.Domains) + if len(cfg.DNSTT.Domains) > 0 { + cfg.DNSTT.Domain = cfg.DNSTT.Domains[0] + } else { + cfg.DNSTT.Domain = strings.TrimSpace(cfg.DNSTT.Domain) + } + if cfg.DNSTT.FakeDNSEnabled { + localDomains := normalizeDNSTTDomainList(cfg.DNSTT.FakeDNSDomain, nil) + if len(localDomains) > 0 { + cfg.DNSTT.FakeDNSDomain = localDomains[0] + } + } + + var migratedLegacyDNSTTWildcard bool + cfg.DNSTT.UDPListen, migratedLegacyDNSTTWildcard = normalizeDNSTTListenDefault(cfg.DNSTT.UDPListen) + if migratedLegacyDNSTTWildcard { + warn("DNSTT legacy default [::]:5300 is IPv6-only; using IPv4 default %s", cfg.DNSTT.UDPListen) + } + if err := udpAddrAvailableForDNSTT(cfg.DNSTT.UDPListen); err != nil { + old := cfg.DNSTT.UDPListen + cfg.DNSTT.UDPListen = defaultDNSTTListen + warn("DNSTT UDP listener %s is unavailable (%v); using default %s", old, err, cfg.DNSTT.UDPListen) + if err2 := udpAddrAvailableForDNSTT(cfg.DNSTT.UDPListen); err2 != nil { + warn("default DNSTT UDP listener %s is also unavailable: %v", cfg.DNSTT.UDPListen, err2) + } + } + + if cfg.DNSTT.FakeDNSEnabled { + cfg.DNSTT.FakeDNSListen = strings.TrimSpace(cfg.DNSTT.FakeDNSListen) + if cfg.DNSTT.FakeDNSListen == "" { + cfg.DNSTT.FakeDNSListen = "[::]:53" + } + if !sameUDPListenAddress(cfg.DNSTT.FakeDNSListen, cfg.DNSTT.UDPListen) { + if err := udpAddrAvailableForDNSTT(cfg.DNSTT.FakeDNSListen); err != nil { + warn("built-in DNSTT local DNS listener %s is unavailable: %v", cfg.DNSTT.FakeDNSListen, err) + } + } + } + + cfg.DNSTT.AutoRestartInterval = strings.TrimSpace(cfg.DNSTT.AutoRestartInterval) + if cfg.DNSTT.AutoRestartInterval != "" && cfg.DNSTT.AutoRestartInterval != "0" && cfg.DNSTT.AutoRestartInterval != "0s" && !strings.EqualFold(cfg.DNSTT.AutoRestartInterval, "off") && !strings.EqualFold(cfg.DNSTT.AutoRestartInterval, "disabled") { + if d, err := time.ParseDuration(cfg.DNSTT.AutoRestartInterval); err != nil { + warn("DNSTT auto restart interval %q is invalid; disabling auto restart", cfg.DNSTT.AutoRestartInterval) + cfg.DNSTT.AutoRestartInterval = "" + } else if d < time.Minute { + warn("DNSTT auto restart interval %q is below 1m; disabling auto restart", cfg.DNSTT.AutoRestartInterval) + cfg.DNSTT.AutoRestartInterval = "" + } + } + cfg.DNSTT.AutoRestartGrace = strings.TrimSpace(cfg.DNSTT.AutoRestartGrace) + if cfg.DNSTT.AutoRestartGrace != "" { + if d, err := time.ParseDuration(cfg.DNSTT.AutoRestartGrace); err != nil || d < 0 { + warn("DNSTT auto restart grace %q is invalid; using default 2s", cfg.DNSTT.AutoRestartGrace) + cfg.DNSTT.AutoRestartGrace = "" + } else if d > time.Minute { + warn("DNSTT auto restart grace %q is above 1m; clamping to 1m", cfg.DNSTT.AutoRestartGrace) + cfg.DNSTT.AutoRestartGrace = "1m" + } + } + + if cfg.DNSTT.MaxSessions < -1 { + warn("DNSTT max_sessions %d is invalid; using unlimited (-1)", cfg.DNSTT.MaxSessions) + cfg.DNSTT.MaxSessions = -1 + } + if cfg.DNSTT.MaxStreams < -1 { + warn("DNSTT max_streams %d is invalid; using unlimited (-1)", cfg.DNSTT.MaxStreams) + cfg.DNSTT.MaxStreams = -1 + } + if cfg.DNSTT.PendingResponses > 0 { + if cfg.DNSTT.PendingResponses < minDNSTTPendingResponses { + warn("DNSTT pending_responses %d is too low; clamping to %d", cfg.DNSTT.PendingResponses, minDNSTTPendingResponses) + cfg.DNSTT.PendingResponses = minDNSTTPendingResponses + } else if cfg.DNSTT.PendingResponses > maxDNSTTPendingResponses { + warn("DNSTT pending_responses %d is too high; clamping to %d", cfg.DNSTT.PendingResponses, maxDNSTTPendingResponses) + cfg.DNSTT.PendingResponses = maxDNSTTPendingResponses + } + } + if cfg.DNSTT.StreamBuffer > 0 { + if cfg.DNSTT.StreamBuffer < minDNSTTStreamBuffer { + warn("DNSTT stream_buffer %d is too low; clamping to %d", cfg.DNSTT.StreamBuffer, minDNSTTStreamBuffer) + cfg.DNSTT.StreamBuffer = minDNSTTStreamBuffer + } else if cfg.DNSTT.StreamBuffer > maxDNSTTStreamBuffer { + warn("DNSTT stream_buffer %d is too high; clamping to %d", cfg.DNSTT.StreamBuffer, maxDNSTTStreamBuffer) + cfg.DNSTT.StreamBuffer = maxDNSTTStreamBuffer + } + } + if cfg.DNSTT.UDPReadBuffer < 0 { + warn("DNSTT udp_read_buffer %d is invalid; using default", cfg.DNSTT.UDPReadBuffer) + cfg.DNSTT.UDPReadBuffer = 0 + } + if cfg.DNSTT.UDPWriteBuffer < 0 { + warn("DNSTT udp_write_buffer %d is invalid; using default", cfg.DNSTT.UDPWriteBuffer) + cfg.DNSTT.UDPWriteBuffer = 0 + } + if cfg.DNSTT.FakeDNSWorkers < 0 { + warn("DNSTT fake_dns_workers %d is invalid; using automatic default", cfg.DNSTT.FakeDNSWorkers) + cfg.DNSTT.FakeDNSWorkers = 0 + } else if cfg.DNSTT.FakeDNSWorkers > maxDNSTTFakeDNSWorkers { + warn("DNSTT fake_dns_workers %d is too high; clamping to %d", cfg.DNSTT.FakeDNSWorkers, maxDNSTTFakeDNSWorkers) + cfg.DNSTT.FakeDNSWorkers = maxDNSTTFakeDNSWorkers + } + if cfg.DNSTT.DNSResponseWorkers < 0 { + warn("DNSTT dns_response_workers %d is invalid; using default", cfg.DNSTT.DNSResponseWorkers) + cfg.DNSTT.DNSResponseWorkers = 0 + } else if cfg.DNSTT.DNSResponseWorkers > maxDNSTTResponseWorkers { + warn("DNSTT dns_response_workers %d is too high; clamping to %d", cfg.DNSTT.DNSResponseWorkers, maxDNSTTResponseWorkers) + cfg.DNSTT.DNSResponseWorkers = maxDNSTTResponseWorkers + } + } + + if cfg.UDPGW != nil { + cfg.UDPGW.Listen = strings.TrimSpace(cfg.UDPGW.Listen) + if cfg.UDPGW.Listen == "" { + cfg.UDPGW.Listen = defaultUDPGWListen + } + if err := tcpAddrAvailableForUDPGW(cfg.UDPGW.Listen); err != nil { + old := cfg.UDPGW.Listen + cfg.UDPGW.Listen = defaultUDPGWListen + warn("UDPGW listener %s is unavailable (%v); using default %s", old, err, cfg.UDPGW.Listen) + if err2 := tcpAddrAvailableForUDPGW(cfg.UDPGW.Listen); err2 != nil { + warn("default UDPGW listener %s is also unavailable: %v", cfg.UDPGW.Listen, err2) + } + } + + cfg.UDPGW.AutoRestartInterval = strings.TrimSpace(cfg.UDPGW.AutoRestartInterval) + if cfg.UDPGW.AutoRestartInterval != "" && cfg.UDPGW.AutoRestartInterval != "0" && cfg.UDPGW.AutoRestartInterval != "0s" && !strings.EqualFold(cfg.UDPGW.AutoRestartInterval, "off") && !strings.EqualFold(cfg.UDPGW.AutoRestartInterval, "disabled") { + if d, err := time.ParseDuration(cfg.UDPGW.AutoRestartInterval); err != nil { + warn("UDPGW auto restart interval %q is invalid; disabling auto restart", cfg.UDPGW.AutoRestartInterval) + cfg.UDPGW.AutoRestartInterval = "" + } else if d < time.Minute { + warn("UDPGW auto restart interval %q is below 1m; disabling auto restart", cfg.UDPGW.AutoRestartInterval) + cfg.UDPGW.AutoRestartInterval = "" + } + } + cfg.UDPGW.AutoRestartGrace = strings.TrimSpace(cfg.UDPGW.AutoRestartGrace) + if cfg.UDPGW.AutoRestartGrace != "" { + if d, err := time.ParseDuration(cfg.UDPGW.AutoRestartGrace); err != nil || d < 0 { + warn("UDPGW auto restart grace %q is invalid; using default 2s", cfg.UDPGW.AutoRestartGrace) + cfg.UDPGW.AutoRestartGrace = "" + } else if d > time.Minute { + warn("UDPGW auto restart grace %q is above 1m; clamping to 1m", cfg.UDPGW.AutoRestartGrace) + cfg.UDPGW.AutoRestartGrace = "1m" + } + } + } + + if cfg.BHTTP != nil { + addrs := normalizeBHTTPListenList(cfg.BHTTP.Listen) + if len(addrs) == 0 && !cfg.BHTTP.SharedPorts { + // With no dedicated listener and no shared ports nothing would + // serve BHTTP at all, so fall back to a port of its own. + addrs = []string{defaultBHTTPListen} + warn("BHTTP has no listen address and shared ports are off; using default %s", defaultBHTTPListen) + } + kept := make([]string, 0, len(addrs)) + for _, addr := range addrs { + if err := tcpAddrAvailableForBHTTP(addr); err != nil { + warn("BHTTP listener %s is unavailable (%v)", addr, err) + continue + } + kept = append(kept, addr) + } + if len(addrs) > 0 && len(kept) == 0 { + warn("no BHTTP listener could be opened; keeping the configured addresses so the panel reports the failure") + kept = addrs + } + cfg.BHTTP.Listen = kept + + normalizeDurationField(&cfg.BHTTP.SessionTimeout, "BHTTP session_timeout", 10*time.Second, time.Hour, warn) + if cfg.BHTTP.MaxV2Lanes < 0 { + warn("BHTTP max_v2_lanes %d is invalid; using the protocol default", cfg.BHTTP.MaxV2Lanes) + cfg.BHTTP.MaxV2Lanes = 0 + } + if cfg.BHTTP.MaxSessions < -1 { + warn("BHTTP max_sessions %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxSessions) + cfg.BHTTP.MaxSessions = -1 + } + if cfg.BHTTP.MaxConnections < -1 { + warn("BHTTP max_connections %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxConnections) + cfg.BHTTP.MaxConnections = -1 + } + normalizeAutoRestartFields(&cfg.BHTTP.AutoRestartInterval, &cfg.BHTTP.AutoRestartGrace, "BHTTP", warn) + } + + if cfg.BTUN != nil { + normalizeBTUNConfig(cfg.BTUN) + if cfg.BTUN.TCPListen == "" && cfg.BTUN.UDPListen == "" && !cfg.BTUN.SharedPorts { + // With no listener and no shared ports nothing would serve BTUN at + // all, so fall back to ports of its own. + cfg.BTUN.TCPListen = defaultBTUNTCPListen + cfg.BTUN.UDPListen = defaultBTUNUDPListen + warn("BTUN has no listener and shared ports are off; using defaults tcp/udp %s", defaultBTUNTCPListen) + } + if cfg.BTUN.TCPListen != "" { + if err := tcpAddrAvailableForBTUN(cfg.BTUN.TCPListen); err != nil { + warn("BTUN TCP listener %s is unavailable (%v)", cfg.BTUN.TCPListen, err) + } + } + if cfg.BTUN.UDPListen != "" { + if err := udpAddrAvailableForBTUN(cfg.BTUN.UDPListen); err != nil { + warn("BTUN UDP listener %s is unavailable (%v)", cfg.BTUN.UDPListen, err) + } + } + if _, _, err := net.ParseCIDR(cfg.BTUN.Subnet); err != nil { + warn("BTUN subnet %q is invalid (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet) + cfg.BTUN.Subnet = defaultBTUNSubnet + cfg.BTUN.Gateway = "" + } + if gateway, err := btunGatewayForSubnet(cfg.BTUN.Subnet); err != nil { + warn("BTUN subnet %q cannot host clients (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet) + cfg.BTUN.Subnet = defaultBTUNSubnet + cfg.BTUN.Gateway, _ = btunGatewayForSubnet(defaultBTUNSubnet) + } else if cfg.BTUN.Gateway == "" { + cfg.BTUN.Gateway = gateway + } else if _, _, err := net.ParseCIDR(cfg.BTUN.Gateway); err != nil { + warn("BTUN gateway %q is invalid (%v); deriving %s from the subnet", cfg.BTUN.Gateway, err, gateway) + cfg.BTUN.Gateway = gateway + } + if cfg.BTUN.MTU < 576 || cfg.BTUN.MTU > 9000 { + warn("BTUN mtu %d is out of the 576..9000 range; using default %d", cfg.BTUN.MTU, defaultBTUNMTU) + cfg.BTUN.MTU = defaultBTUNMTU + } + normalizeDurationField(&cfg.BTUN.HandshakeTimeout, "BTUN handshake_timeout", time.Second, 5*time.Minute, warn) + normalizeDurationField(&cfg.BTUN.IdleTimeout, "BTUN idle_timeout", 10*time.Second, time.Hour, warn) + if cfg.BTUN.MaxPacketSize < 0 { + warn("BTUN max_packet_size %d is invalid; using the protocol default", cfg.BTUN.MaxPacketSize) + cfg.BTUN.MaxPacketSize = 0 + } + if cfg.BTUN.MaxCoverBytes < 0 { + warn("BTUN max_cover_bytes %d is invalid; using the protocol default", cfg.BTUN.MaxCoverBytes) + cfg.BTUN.MaxCoverBytes = 0 + } + if cfg.BTUN.MaxSessions < -1 { + warn("BTUN max_sessions %d is invalid; using unlimited (-1)", cfg.BTUN.MaxSessions) + cfg.BTUN.MaxSessions = -1 + } + normalizeAutoRestartFields(&cfg.BTUN.AutoRestartInterval, &cfg.BTUN.AutoRestartGrace, "BTUN", warn) + } + + if cfg.HCR != nil { + addrs := normalizeHCRListenList(cfg.HCR.Listen) + if len(addrs) == 0 && !cfg.HCR.SharedPorts { + addrs = []string{defaultHCRListen} + warn("HCR has no listen address and shared ports are off; using default %s", defaultHCRListen) + } + kept := make([]string, 0, len(addrs)) + for _, addr := range addrs { + if err := tcpAddrAvailableForHCR(addr); err != nil { + warn("HCR listener %s is unavailable (%v)", addr, err) + continue + } + kept = append(kept, addr) + } + if len(addrs) > 0 && len(kept) == 0 { + warn("no HCR listener could be opened; keeping the configured addresses so the panel reports the failure") + kept = addrs + } + cfg.HCR.Listen = kept + + normalizeDurationField(&cfg.HCR.DownloadPollTimeout, "HCR download_poll_timeout", time.Second, time.Minute, warn) + normalizeDurationField(&cfg.HCR.IdleSessionTimeout, "HCR idle_session_timeout", 10*time.Second, time.Hour, warn) + if cfg.HCR.MaxSessions < -1 { + warn("HCR max_sessions %d is invalid; using unlimited (-1)", cfg.HCR.MaxSessions) + cfg.HCR.MaxSessions = -1 + } + if cfg.HCR.MaxConnections < -1 { + warn("HCR max_connections %d is invalid; using unlimited (-1)", cfg.HCR.MaxConnections) + cfg.HCR.MaxConnections = -1 + } + if cfg.HCR.MaxSourceSessions < 0 { + warn("HCR max_source_sessions %d is invalid; using 0 (unlimited)", cfg.HCR.MaxSourceSessions) + cfg.HCR.MaxSourceSessions = 0 + } + if cfg.HCR.MaxDownloadFrame < 0 { + warn("HCR max_download_frame %d is invalid; using the default", cfg.HCR.MaxDownloadFrame) + cfg.HCR.MaxDownloadFrame = 0 + } + normalizeAutoRestartFields(&cfg.HCR.AutoRestartInterval, &cfg.HCR.AutoRestartGrace, "HCR", warn) + } + + return warnings +} + +// tcpAddrAvailableForHCR reports whether an HCR listen address can be bound. An +// address this process already serves for HCR is treated as available. +func tcpAddrAvailableForHCR(addr string) error { + if addr == "" { + return nil + } + if hcrRunning() { + for _, current := range strings.Split(hcrListenList(), ", ") { + if strings.TrimSpace(current) == addr { + return nil + } + } + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + +// tcpAddrAvailableForBHTTP reports whether a BHTTP listen address can be bound. +// An address this process already serves for BHTTP is treated as available, so +// saving an unchanged config does not report a false conflict. +func tcpAddrAvailableForBHTTP(addr string) error { + if addr == "" { + return nil + } + if bhttpRunning() { + for _, current := range strings.Split(bhttpListenList(), ", ") { + if strings.TrimSpace(current) == addr { + return nil + } + } + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + +func tcpAddrAvailableForBTUN(addr string) error { + if addr == "" { + return nil + } + btunMu.Lock() + current := btunListenTCP + running := btunServer != nil + btunMu.Unlock() + if running && current == addr { + return nil + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + +func udpAddrAvailableForBTUN(addr string) error { + if addr == "" { + return nil + } + btunMu.Lock() + current := btunListenUDP + running := btunServer != nil + btunMu.Unlock() + if running && current == addr { + return nil + } + pc, err := net.ListenPacket("udp", addr) + if err != nil { + return err + } + return pc.Close() +} + +// normalizeLocalSSHListen guarantees that the raw integration endpoint can +// only bind to this machine. Hostnames and wildcard/non-loopback addresses are +// deliberately rejected: a changed hosts file must not turn an internal SSH +// port into a remotely reachable service. +func normalizeLocalSSHListen(addr string) (string, error) { + addr = strings.TrimSpace(addr) + if addr == "" { + return defaultLocalSSHListen, nil + } + + host, portText, err := net.SplitHostPort(addr) + if err != nil { + return defaultLocalSSHListen, fmt.Errorf("expected loopback host:port: %w", err) + } + ip := net.ParseIP(host) + if ip == nil || !ip.IsLoopback() { + return defaultLocalSSHListen, fmt.Errorf("host must be a numeric loopback IP") + } + port, err := strconv.Atoi(portText) + if err != nil || port < 1 || port > 65535 { + return defaultLocalSSHListen, fmt.Errorf("port must be between 1 and 65535") + } + if ipv4 := ip.To4(); ipv4 != nil { + ip = ipv4 + } + return net.JoinHostPort(ip.String(), strconv.Itoa(port)), nil +} + +func tcpAddrAvailableForPool(addr string, pool *listenerPool) error { + if addr == "" { + return nil + } + if pool != nil && pool.Has(addr) { + return nil + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + +func tcpAddrAvailableForUDPGW(addr string) error { + if addr == "" { + return nil + } + globalCfgMu.RLock() + current := globalCfg != nil && globalCfg.UDPGW != nil && globalCfg.UDPGW.Listen == addr && udpgwRunning() + globalCfgMu.RUnlock() + if current { + return nil + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + +func normalizeDNSTTDomainList(primary string, domains []string) []string { + seen := make(map[string]bool, len(domains)+1) + out := make([]string, 0, len(domains)+1) + add := func(v string) { + v = strings.TrimSpace(v) + v = strings.TrimSuffix(v, ".") + v = strings.ToLower(v) + if v == "" || seen[v] { + return + } + seen[v] = true + out = append(out, v) + } + add(primary) + for _, d := range domains { + add(d) + } + return out +} + +// normalizeDNSTTListenDefault keeps explicit IPv4 and concrete IPv6 listeners, +// but migrates the old wildcard IPv6 default. listenDNSTTPacket deliberately +// opens IPv6 addresses with udp6, so [::]:5300 never receives IPv4 queries. +// Existing installations commonly inherited that value from the old default; +// moving only that wildcard/default-port combination makes them work after an +// update without changing intentionally selected IPv6 interface addresses. +func normalizeDNSTTListenDefault(addr string) (string, bool) { + addr = strings.TrimSpace(addr) + if addr == "" { + return defaultDNSTTListen, false + } + + host, port, err := net.SplitHostPort(addr) + if err != nil || port != "5300" { + return addr, false + } + ip := net.ParseIP(strings.Trim(host, "[]")) + if ip != nil && ip.To4() == nil && ip.IsUnspecified() { + return defaultDNSTTListen, true + } + return addr, false +} + +func udpAddrAvailableForDNSTT(addr string) error { + if addr == "" { + return nil + } + globalCfgMu.RLock() + current := false + if globalCfg != nil && globalCfg.DNSTT != nil && dnsttRunning() { + current = sameUDPListenAddress(globalCfg.DNSTT.UDPListen, addr) || sameUDPListenAddress(globalCfg.DNSTT.FakeDNSListen, addr) + } + globalCfgMu.RUnlock() + if current { + return nil + } + pc, err := listenDNSTTPacket(addr) + if err != nil { + return err + } + return pc.Close() +} diff --git a/config_safety_test.go b/config_safety_test.go new file mode 100644 index 0000000..e941185 --- /dev/null +++ b/config_safety_test.go @@ -0,0 +1,64 @@ +package main + +import "testing" + +func TestNormalizeLocalSSHListen(t *testing.T) { + tests := []struct { + name string + input string + want string + wantErr bool + }{ + {name: "empty uses safe default", input: "", want: defaultLocalSSHListen}, + {name: "whitespace uses safe default", input: " ", want: defaultLocalSSHListen}, + {name: "IPv4 loopback", input: "127.0.0.1:2200", want: "127.0.0.1:2200"}, + {name: "other IPv4 loopback", input: "127.10.20.30:2222", want: "127.10.20.30:2222"}, + {name: "IPv6 loopback", input: "[::1]:2222", want: "[::1]:2222"}, + {name: "wildcard IPv4 rejected", input: "0.0.0.0:2222", want: defaultLocalSSHListen, wantErr: true}, + {name: "wildcard IPv6 rejected", input: "[::]:2222", want: defaultLocalSSHListen, wantErr: true}, + {name: "public address rejected", input: "192.0.2.10:2222", want: defaultLocalSSHListen, wantErr: true}, + {name: "hostname rejected", input: "localhost:2222", want: defaultLocalSSHListen, wantErr: true}, + {name: "missing port rejected", input: "127.0.0.1", want: defaultLocalSSHListen, wantErr: true}, + {name: "zero port rejected", input: "127.0.0.1:0", want: defaultLocalSSHListen, wantErr: true}, + {name: "large port rejected", input: "127.0.0.1:65536", want: defaultLocalSSHListen, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := normalizeLocalSSHListen(tt.input) + if got != tt.want { + t.Fatalf("normalizeLocalSSHListen(%q) address = %q, want %q", tt.input, got, tt.want) + } + if (err != nil) != tt.wantErr { + t.Fatalf("normalizeLocalSSHListen(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr) + } + }) + } +} + +func TestNormalizeDNSTTListenDefault(t *testing.T) { + tests := []struct { + name string + input string + want string + migrated bool + }{ + {name: "empty uses IPv4 default", input: "", want: "0.0.0.0:5300"}, + {name: "whitespace uses IPv4 default", input: " ", want: "0.0.0.0:5300"}, + {name: "legacy IPv6 wildcard migrates", input: "[::]:5300", want: "0.0.0.0:5300", migrated: true}, + {name: "expanded legacy wildcard migrates", input: "[0:0:0:0:0:0:0:0]:5300", want: "0.0.0.0:5300", migrated: true}, + {name: "explicit IPv4 remains", input: "192.0.2.10:53", want: "192.0.2.10:53"}, + {name: "IPv4 wildcard remains", input: "0.0.0.0:5300", want: "0.0.0.0:5300"}, + {name: "concrete IPv6 remains", input: "[2001:db8::10]:53", want: "[2001:db8::10]:53"}, + {name: "IPv6 wildcard on custom port remains", input: "[::]:5301", want: "[::]:5301"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, migrated := normalizeDNSTTListenDefault(tt.input) + if got != tt.want || migrated != tt.migrated { + t.Fatalf("normalizeDNSTTListenDefault(%q) = (%q, %v), want (%q, %v)", tt.input, got, migrated, tt.want, tt.migrated) + } + }) + } +} diff --git a/connection_lifetime_test.go b/connection_lifetime_test.go new file mode 100644 index 0000000..e35617b --- /dev/null +++ b/connection_lifetime_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "testing" + "time" +) + +func TestSSHIdleTimeoutDisabledByDefault(t *testing.T) { + for _, raw := range []string{"", "0", "0s", "off", "disabled"} { + if got := parseSSHIdleTimeout(raw); got != 0 { + t.Fatalf("parseSSHIdleTimeout(%q) = %s, want disabled", raw, got) + } + } +} + +func TestSSHIdleTimeoutExplicitValue(t *testing.T) { + if got := parseSSHIdleTimeout("30m"); got != 30*time.Minute { + t.Fatalf("got %s, want 30m", got) + } +} + +// The connected-session sweeper is the backstop that reaps XHTTP->SSH sessions +// whose stream-down GET context never fires (silent client drop behind a CDN). +// Without it those sessions leak fds/goroutines until a process restart, which +// is what produced the recurring reboot-only XHTTP 502s. It must stay enabled; +// the window is generous so only zero-traffic (dead) sessions are reaped. +func TestNativeXHTTPConnectedIdleSweepEnabled(t *testing.T) { + got := nativeXHTTPIdleTimeout() + if got <= 0 { + t.Fatalf("native XHTTP idle timeout = %s, want a positive backstop window", got) + } + if got != 20*time.Minute { + t.Fatalf("native XHTTP idle timeout = %s, want 20m backstop", got) + } +} diff --git a/credential_crypto.go b/credential_crypto.go new file mode 100644 index 0000000..228d46c --- /dev/null +++ b/credential_crypto.go @@ -0,0 +1,29 @@ +package main + +import ( + "encoding/base64" + "fmt" + "strings" +) + +func sealCredential(prefix, plain string) (string, error) { + if plain == "" || strings.HasPrefix(plain, prefix) { + return plain, nil + } + enc, err := encryptSecret(plain) + if err != nil { + return "", err + } + return prefix + base64.RawStdEncoding.EncodeToString(enc), nil +} + +func openCredential(prefix, stored string) (string, error) { + if !strings.HasPrefix(stored, prefix) { + return stored, nil + } + raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(stored, prefix)) + if err != nil { + return "", fmt.Errorf("decode encrypted credential: %w", err) + } + return decryptSecret(raw) +} diff --git a/descrypt.go b/descrypt.go new file mode 100644 index 0000000..daeb87f --- /dev/null +++ b/descrypt.go @@ -0,0 +1,232 @@ +package main + +import ( + "errors" + "strings" +) + +// Traditional DES-based crypt(3) — the 13-character, no-"$"-prefix hash used by +// old Linux/UNIX systems (e.g. accounts created with perl's crypt() or legacy +// SSH-account scripts). Pure Go; no dependency on libcrypt. +// +// Verified against the canonical vector crypt("rasmuslerdorf","rl") == +// "rl.3StKT.4T8M" (see descrypt_test.go). + +const cryptAlphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +func crypt64Decode(c byte) int { + return strings.IndexByte(cryptAlphabet, c) +} + +// ---- Standard DES permutation tables (1-indexed, MSB-first) ---- + +var ipTable = []int{ + 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, +} + +var fpTable = []int{ + 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, +} + +var eTable = []int{ + 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1, +} + +var pTable = []int{ + 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25, +} + +var pc1Table = []int{ + 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4, +} + +var pc2Table = []int{ + 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32, +} + +var shiftTable = []int{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1} + +var sBoxes = [8][64]int{ + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, + 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, + 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, + 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, + 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, + 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, + 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, + 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, + 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, + 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, + 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, + 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, + 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, + 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, + 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, + 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, + 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, + 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, + 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, + 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, + 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, + 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, + 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, + 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, + 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}, +} + +// permute selects bits from in (each element 0/1, MSB-first) per a 1-indexed table. +func permute(in []byte, table []int) []byte { + out := make([]byte, len(table)) + for i, pos := range table { + out[i] = in[pos-1] + } + return out +} + +func keySchedule(key64 []byte) [][]byte { + cd := permute(key64, pc1Table) // 56 bits + c := cd[:28] + d := cd[28:] + subkeys := make([][]byte, 16) + for i := 0; i < 16; i++ { + c = rotl(c, shiftTable[i]) + d = rotl(d, shiftTable[i]) + combined := append(append([]byte{}, c...), d...) + subkeys[i] = permute(combined, pc2Table) // 48 bits + } + return subkeys +} + +func rotl(b []byte, n int) []byte { + out := make([]byte, len(b)) + for i := range b { + out[i] = b[(i+n)%len(b)] + } + return out +} + +// feistel computes f(R, K) with the salt-perturbed E expansion. +func feistel(r []byte, k []byte, saltMask [24]bool) []byte { + e := permute(r, eTable) // 48 bits + // Salt: for i in 0..23, if saltMask[i] swap E-output bits i and i+24. + for i := 0; i < 24; i++ { + if saltMask[i] { + e[i], e[i+24] = e[i+24], e[i] + } + } + x := make([]byte, 48) + for i := range x { + x[i] = e[i] ^ k[i] + } + out := make([]byte, 32) + for box := 0; box < 8; box++ { + off := box * 6 + row := int(x[off])<<1 | int(x[off+5]) + col := int(x[off+1])<<3 | int(x[off+2])<<2 | int(x[off+3])<<1 | int(x[off+4]) + val := sBoxes[box][row*16+col] + for bit := 0; bit < 4; bit++ { + out[box*4+bit] = byte((val >> (3 - bit)) & 1) + } + } + return permute(out, pTable) +} + +func desEncryptBlock(block []byte, subkeys [][]byte, saltMask [24]bool) []byte { + ip := permute(block, ipTable) + l := ip[:32] + r := ip[32:] + for i := 0; i < 16; i++ { + f := feistel(r, subkeys[i], saltMask) + newR := make([]byte, 32) + for j := 0; j < 32; j++ { + newR[j] = l[j] ^ f[j] + } + l = r + r = newR + } + pre := append(append([]byte{}, r...), l...) // R16 L16 + return permute(pre, fpTable) +} + +// desCrypt implements the traditional 13-char DES crypt. setting supplies the +// 2-char salt (its first two characters). +func desCrypt(password, setting string) (string, error) { + if len(setting) < 2 { + return "", errors.New("descrypt: salt too short") + } + s0 := crypt64Decode(setting[0]) + s1 := crypt64Decode(setting[1]) + if s0 < 0 || s1 < 0 { + return "", errors.New("descrypt: bad salt characters") + } + salt := s0 | (s1 << 6) + var saltMask [24]bool + for i := 0; i < 24; i++ { + if (salt>>i)&1 == 1 { + saltMask[i] = true + } + } + + // Key: first 8 bytes of the password, each char<<1 forms a key byte. + key64 := make([]byte, 64) + for i := 0; i < 8; i++ { + var c byte + if i < len(password) { + c = password[i] + } + kb := c << 1 + for bit := 0; bit < 8; bit++ { + key64[i*8+bit] = (kb >> (7 - bit)) & 1 + } + } + subkeys := keySchedule(key64) + + block := make([]byte, 64) // all zeros + for iter := 0; iter < 25; iter++ { + block = desEncryptBlock(block, subkeys, saltMask) + } + + return string(setting[0]) + string(setting[1]) + encodeDESOutput(block), nil +} + +// encodeDESOutput packs the 64-bit result (MSB-first bit array) into 11 +// crypt-base64 characters: eleven 6-bit groups read most-significant-bit first, +// the last group zero-padded to 6 bits. +func encodeDESOutput(block []byte) string { + out := make([]byte, 0, 11) + for j := 0; j < 11; j++ { + v := 0 + for k := 0; k < 6; k++ { + idx := j*6 + k + bit := 0 + if idx < len(block) { + bit = int(block[idx]) + } + v = (v << 1) | bit + } + out = append(out, cryptAlphabet[v]) + } + return string(out) +} diff --git a/descrypt_test.go b/descrypt_test.go new file mode 100644 index 0000000..18ffab9 --- /dev/null +++ b/descrypt_test.go @@ -0,0 +1,15 @@ +package main + +import "testing" + +func TestDESCryptCanonical(t *testing.T) { + got, err := desCrypt("rasmuslerdorf", "rl") + if err != nil { + t.Fatal(err) + } + want := "rl.3StKT.4T8M" + t.Logf("got=%q want=%q", got, want) + if got != want { + t.Errorf("desCrypt mismatch: got %q want %q", got, want) + } +} diff --git a/dnstt_integration.go b/dnstt_integration.go new file mode 100644 index 0000000..d08b7bc --- /dev/null +++ b/dnstt_integration.go @@ -0,0 +1,1893 @@ +package main + +// This file integrates a minimal DNS‑tunnel server (dnstt) into the main +// application. It is adapted from the public‑domain dnstt-server project +// (see https://www.bamsoftware.com/software/dnstt/) but modified to +// terminate streams into the existing SSH handler (handleConn) rather than +// forwarding them to an upstream TCP service. Each stream accepted via +// dnstt is wrapped as a net.Conn and passed to handleConn. The DNS +// transport itself uses KCP over UDP, Noise encryption and smux +// multiplexing as in the original dnstt. + +import ( + "bytes" + "context" + "encoding/base32" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "os" + "runtime" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/xtaci/kcp-go/v5" + "github.com/xtaci/smux" + "golang.org/x/crypto/ssh" + "www.bamsoftware.com/git/dnstt.git/dns" + "www.bamsoftware.com/git/dnstt.git/noise" + + // Local fork of the upstream turbotunnel package. Identical except that + // RemoteMap's background expiry goroutine is stoppable via Close(); upstream + // leaks it for the process lifetime, which becomes a per-restart goroutine + // leak under this integration's DNSTT hot-reload / auto-restart. + "shell2/internal/turbotunnel" +) + +// ---------- Hot-reload stop mechanism ---------- + +var ( + dnsttConnMu sync.Mutex + // active UDP sockets; closing them stops every DNSTT DNS listener. There may + // be more than one when the built-in local/fake DNS listener is enabled. + dnsttConns []net.PacketConn + + dnsttAutoMu sync.Mutex + dnsttAutoCancel context.CancelFunc +) + +// stopDNSTT closes the active DNSTT UDP listener and stops the optional +// auto-restart watchdog. It is a no-op if DNSTT is not running. +func stopDNSTT() { + stopDNSTTAutoRestart() + stopDNSTTListener() +} + +// stopDNSTTListener closes only the UDP listener. The auto-restart watchdog +// uses this helper so it can cycle DNSTT without disabling itself. +func stopDNSTTListener() { + dnsttConnMu.Lock() + defer dnsttConnMu.Unlock() + for _, c := range dnsttConns { + if c != nil { + _ = c.Close() + } + } + dnsttConns = nil +} + +func stopDNSTTAutoRestart() { + dnsttAutoMu.Lock() + defer dnsttAutoMu.Unlock() + if dnsttAutoCancel != nil { + dnsttAutoCancel() + dnsttAutoCancel = nil + } +} + +// Constants mirrored from dnstt-server. See dnstt-server/main.go for +// commentary. +const ( + // smux streams will be closed after this much time without receiving data. + idleTimeout = 2 * time.Minute + // How to set the TTL field in Answer resource records. + responseTTL = 60 + // How long we may wait for downstream data before sending an empty + // response. This number should be less than 2 seconds (Quad9 DNS + // timeout as of 2019). + maxResponseDelay = 1 * time.Second +) + +// We don't send UDP payloads larger than this, in an attempt to avoid +// network-layer fragmentation. 1280 is the minimum IPv6 MTU, 40 bytes is +// the size of an IPv6 header (without extension headers), and 8 bytes is +// the size of a UDP header【561853413345496†L97-L109】. +// Control this value with the -mtu command-line option in the standalone +// dnstt-server. Here we use the default. +// maxUDPPayload defines the maximum UDP payload we ever send in a DNS +// response. It defaults to the IPv6 minimum MTU minus the IPv6 and UDP +// header sizes (1232 octets) but is clamped per‑query in responseFor and +// sendLoop based on the EDNS UDP payload advertised by the client. See +// startDNSTT for how this may be overridden via configuration. +var maxUDPPayload = 1280 - 40 - 8 + +// noEDNSFallbackPayload is the assumed UDP payload capability for resolver +// paths that do not include an EDNS(0) OPT RR (or that clamp it to 512) but +// still reliably carry larger UDP DNS messages. Many DNSTT deployments rely +// on this behaviour in the wild. This value is used as a *floor* for the +// inferred payload limit and is still clamped by maxUDPPayload. +// +// If you want strict RFC behaviour, set this to 512. +const noEDNSFallbackPayload = 932 + +const ( + defaultDNSTTMaxSessions = 10000 + defaultDNSTTMaxStreams = 15000 + defaultDNSTTPendingResponses = 20000 + defaultDNSTTStreamBuffer = 256 * 1024 + defaultDNSTTUDPBuffer = 16 * 1024 * 1024 + defaultDNSTTResponseWorkers = 1 + maxDNSTTFakeDNSWorkers = 64 + maxDNSTTResponseWorkers = 16 + minDNSTTStreamBuffer = 64 * 1024 + maxDNSTTStreamBuffer = 2 * 1024 * 1024 + minDNSTTPendingResponses = 1024 + maxDNSTTPendingResponses = 200000 +) + +type dnsttRuntimeLimits struct { + MaxSessions int + MaxStreams int + PendingResponses int + StreamBuffer int + UDPReadBuffer int + UDPWriteBuffer int + FakeDNSWorkers int + DNSResponseWorkers int +} + +// dnsttPrintStats controls whether periodic statistics are printed to stderr. +// It is set based on the DNSTT configuration provided by the main program. +// When false, the periodic stats will still be collected and made available +// via the admin API, but no log lines will be emitted. The default is +// true to preserve existing behaviour. +var dnsttPrintStats = true + +// dnsttLogConnections controls high-volume per-session/per-stream logs. It is +// intentionally false by default because thousands of users can turn logging +// into the bottleneck and make the process unstable. +var dnsttLogConnections atomic.Bool + +// DnsttStatsSnapshot holds a recent snapshot of DNSTT counters over the +// previous 5‑second window. It is updated every 5 seconds by the +// runDNSTT goroutine. The Timestamp field records when the snapshot was +// taken. These values are surfaced via the admin API so that the web +// panel can display tunnel health without reading stderr logs. +type DnsttStatsSnapshot struct { + Timestamp time.Time `json:"timestamp"` + Enabled bool `json:"enabled"` + Running bool `json:"running"` + DNSRx uint64 `json:"dns_rx"` + ParseErr uint64 `json:"parse_err"` + NoEDNS uint64 `json:"no_edns"` + Limit512 uint64 `json:"limit512"` + RecQueued uint64 `json:"rec_queued"` + RecDropped uint64 `json:"rec_dropped"` + RespSent uint64 `json:"resp_sent"` + RespBytes uint64 `json:"resp_bytes"` + RespEmpty uint64 `json:"resp_empty"` + RespData uint64 `json:"resp_data"` + RespOversize uint64 `json:"resp_oversize"` + KCPNew uint64 `json:"kcp_new"` + KCPEnd uint64 `json:"kcp_end"` + SmuxNew uint64 `json:"smux_new"` + SmuxEnd uint64 `json:"smux_end"` + SessRejected uint64 `json:"sess_rejected"` + StreamRejected uint64 `json:"stream_rejected"` + PanicRecovered uint64 `json:"panic_recovered"` + ActiveSessions int64 `json:"active_sessions"` + ActiveStreams int64 `json:"active_streams"` + ChLen int `json:"ch_len"` + FakeDNSWorkers int `json:"fake_dns_workers,omitempty"` + DNSResponseWorkers int `json:"dns_response_workers,omitempty"` +} + +var ( + dnsttStatsMu sync.Mutex + lastDnsttStats DnsttStatsSnapshot +) + +// GetDNSTTStatsSnapshot returns the most recent DNSTT stats snapshot. +// It is safe for concurrent use by HTTP handlers and always returns a +// defensive copy of the snapshot. +func GetDNSTTStatsSnapshot() DnsttStatsSnapshot { + dnsttStatsMu.Lock() + snap := lastDnsttStats + dnsttStatsMu.Unlock() + snap.Enabled = dnsttEnabledInCurrentConfig() + snap.Running = dnsttRunning() + snap.ActiveSessions = atomic.LoadInt64(&dnsttActiveSessions) + snap.ActiveStreams = atomic.LoadInt64(&dnsttActiveStreams) + return snap +} + +func dnsttEnabledInCurrentConfig() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.DNSTT != nil +} + +func defaultDNSTTFakeDNSWorkers() int { + n := runtime.GOMAXPROCS(0) + if n < 2 { + return 2 + } + if n > 8 { + return 8 + } + return n +} + +func dnsttLimitsFromConfig(cfg *DNSTTConfig) dnsttRuntimeLimits { + limits := dnsttRuntimeLimits{ + MaxSessions: defaultDNSTTMaxSessions, + MaxStreams: defaultDNSTTMaxStreams, + PendingResponses: defaultDNSTTPendingResponses, + StreamBuffer: defaultDNSTTStreamBuffer, + UDPReadBuffer: defaultDNSTTUDPBuffer, + UDPWriteBuffer: defaultDNSTTUDPBuffer, + FakeDNSWorkers: defaultDNSTTFakeDNSWorkers(), + DNSResponseWorkers: defaultDNSTTResponseWorkers, + } + if cfg == nil { + return limits + } + if cfg.MaxSessions != 0 { + limits.MaxSessions = cfg.MaxSessions + } + if cfg.MaxStreams != 0 { + limits.MaxStreams = cfg.MaxStreams + } + if cfg.PendingResponses > 0 { + limits.PendingResponses = cfg.PendingResponses + } + if limits.PendingResponses < minDNSTTPendingResponses { + limits.PendingResponses = minDNSTTPendingResponses + } + if limits.PendingResponses > maxDNSTTPendingResponses { + limits.PendingResponses = maxDNSTTPendingResponses + } + if cfg.StreamBuffer > 0 { + limits.StreamBuffer = cfg.StreamBuffer + } + if limits.StreamBuffer < minDNSTTStreamBuffer { + limits.StreamBuffer = minDNSTTStreamBuffer + } + if limits.StreamBuffer > maxDNSTTStreamBuffer { + limits.StreamBuffer = maxDNSTTStreamBuffer + } + if cfg.UDPReadBuffer > 0 { + limits.UDPReadBuffer = cfg.UDPReadBuffer + } + if cfg.UDPWriteBuffer > 0 { + limits.UDPWriteBuffer = cfg.UDPWriteBuffer + } + if cfg.FakeDNSWorkers > 0 { + limits.FakeDNSWorkers = cfg.FakeDNSWorkers + } + if limits.FakeDNSWorkers < 1 { + limits.FakeDNSWorkers = 1 + } + if limits.FakeDNSWorkers > maxDNSTTFakeDNSWorkers { + limits.FakeDNSWorkers = maxDNSTTFakeDNSWorkers + } + if cfg.DNSResponseWorkers > 0 { + limits.DNSResponseWorkers = cfg.DNSResponseWorkers + } + if limits.DNSResponseWorkers < 1 { + limits.DNSResponseWorkers = 1 + } + if limits.DNSResponseWorkers > maxDNSTTResponseWorkers { + limits.DNSResponseWorkers = maxDNSTTResponseWorkers + } + if limits.DNSResponseWorkers > limits.PendingResponses { + limits.DNSResponseWorkers = limits.PendingResponses + } + return limits +} + +func dnsttRecover(where string) { + if r := recover(); r != nil { + atomic.AddUint64(&dnsttStats.PanicRecovered, 1) + dnsttLog.Printf("panic recovered in %s: %v", where, r) + } +} + +func dnsttLogDropEvery(counter uint64, format string, args ...interface{}) { + if counter == 1 || counter%1000 == 0 { + dnsttLog.Printf(format, args...) + } +} + +// dnsttCounters holds aggregated counters used to debug tunnel instability. +// All fields are updated via sync/atomic. +type dnsttCounters struct { + // StreamSeq is a monotonically increasing identifier used to tag smux + // streams as they are handed off to the SSH handler. + StreamSeq uint64 + DNSRx uint64 + DNSParseErr uint64 + // NoEDNS counts DNS queries without an EDNS(0) OPT RR. In many real-world + // deployments (especially mobile / carrier resolvers), EDNS may be stripped + // even though the path can carry UDP responses larger than 512 bytes. + NoEDNS uint64 + // SmallEDNS counts queries where the inferred/advertised UDP payload limit + // is at the classic DNS size (512 bytes). Kept for backward-compatible + // stats output. + SmallEDNS uint64 + RecQueued uint64 + RecDropped uint64 + RespSent uint64 + RespSentBytes uint64 + RespEmpty uint64 + RespWithData uint64 + RespOversize uint64 + KCPSessionsNew uint64 + KCPSessionsEnd uint64 + SmuxStreamsNew uint64 + SmuxStreamsEnd uint64 + SessRejected uint64 + StreamRejected uint64 + PanicRecovered uint64 +} + +var dnsttStats dnsttCounters + +var ( + dnsttActiveSessions int64 + dnsttActiveStreams int64 +) + +var maxEncodedPayloadCache sync.Map // map[int]int + +// dnsttClientPayloadCap tracks an inferred per-client UDP payload capability. +// Keyed by the turbotunnel "remote address" string (a hex ClientID). We use +// this to set a per-session KCP MTU so the tunnel can function on paths that +// do not send EDNS(0) but still support UDP payloads > 512. +// dnsttClientPayloadCap stores per-client capability with a last-seen timestamp. +// This needs periodic cleanup to avoid unbounded growth when many unique client +// IDs are observed over time. +type clientCapEntry struct { + Cap int + LastSeen int64 // unix nano +} + +var dnsttClientPayloadCap sync.Map // map[string]clientCapEntry + +var dnsttCapReaperOnce sync.Once + +func startDNSTTCapReaper() { + // Reap old client capability entries so the map can't grow forever. + // Defaults chosen to be conservative: keep "active" client IDs for 6 hours. + const ( + reapEvery = 10 * time.Minute + maxAge = 6 * time.Hour + ) + dnsttCapReaperOnce.Do(func() { + go func() { + t := time.NewTicker(reapEvery) + defer t.Stop() + for range t.C { + cutoff := time.Now().Add(-maxAge).UnixNano() + dnsttClientPayloadCap.Range(func(k, v any) bool { + e, ok := v.(clientCapEntry) + if ok && e.LastSeen > 0 && e.LastSeen < cutoff { + dnsttClientPayloadCap.Delete(k) + } + return true + }) + } + }() + }) +} + +func dnsttClientKey(clientID turbotunnel.ClientID) string { + return fmt.Sprintf("%x", clientID[:]) +} + +func updateClientPayloadCap(clientID turbotunnel.ClientID, cap int) { + if cap <= 0 { + return + } + key := dnsttClientKey(clientID) + now := time.Now().UnixNano() + if v, ok := dnsttClientPayloadCap.Load(key); ok { + e := v.(clientCapEntry) + if cap > e.Cap { + e.Cap = cap + } + e.LastSeen = now + dnsttClientPayloadCap.Store(key, e) + return + } + dnsttClientPayloadCap.Store(key, clientCapEntry{Cap: cap, LastSeen: now}) +} + +func cachedMaxEncodedPayload(limit int) int { + if limit <= 0 { + return 0 + } + if v, ok := maxEncodedPayloadCache.Load(limit); ok { + return v.(int) + } + m := computeMaxEncodedPayload(limit) + maxEncodedPayloadCache.Store(limit, m) + return m +} + +// base32Encoding is a base32 encoding without padding, as used by dnstt. +var base32Encoding = base32.StdEncoding.WithPadding(base32.NoPadding) + +// dnsttSSHConfig holds the SSH server configuration used by the DNS tunnel. +// It is set by startDNSTT before any dnstt sessions are accepted. +var dnsttSSHConfig *ssh.ServerConfig + +// dnsttLog is a dedicated logger for the integrated DNSTT server. It writes +// to stderr and uses a per-log prefix and microsecond precision. Unlike the +// global log.Logger used by the rest of the application, this logger is not +// affected by calls to log.SetOutput in main.go (e.g. when quiet mode is +// enabled). All log lines emitted by DNSTT should go through dnsttLog so +// that debugging output remains visible even when other logs are suppressed. +var dnsttLog = log.New(os.Stderr, "dnstt: ", log.LstdFlags|log.Lmicroseconds) + +// dnsttLogBuf stores recent DNSTT log lines for the web panel. It acts as a +// circular buffer retaining the last N log lines. The capacity is set when +// the DNSTT server is started, typically around 100 lines to stay well +// within the configured memory budget. Lines are stored without the +// trailing newline. Access to the buffer is synchronized by an internal +// mutex. +type dnsttLogBuffer struct { + mu sync.Mutex + lines []string + maxLines int +} + +// newDNSTTLogBuffer constructs a new ring buffer with the given capacity. +// The capacity must be positive. +func newDNSTTLogBuffer(maxLines int) *dnsttLogBuffer { + if maxLines <= 0 { + maxLines = 100 + } + return &dnsttLogBuffer{ + lines: make([]string, 0, maxLines), + maxLines: maxLines, + } +} + +// Write implements io.Writer and appends complete lines from p to the +// buffer. It splits on '\n' and discards empty segments. When the +// buffer reaches its maximum length, the oldest lines are removed to make +// room for new ones. +func (b *dnsttLogBuffer) Write(p []byte) (n int, err error) { + b.mu.Lock() + defer b.mu.Unlock() + s := string(p) + // Split incoming data by newline. We intentionally discard empty + // strings to avoid blank lines from being stored. + parts := strings.Split(s, "\n") + for _, part := range parts { + if part == "" { + continue + } + if len(b.lines) < b.maxLines { + b.lines = append(b.lines, part) + } else { + // Shift left by one and append new line at end. + copy(b.lines, b.lines[1:]) + b.lines[len(b.lines)-1] = part + } + } + return len(p), nil +} + +// GetLines returns a copy of the current log lines. The lines are +// returned in chronological order from oldest to newest. +func (b *dnsttLogBuffer) GetLines() []string { + b.mu.Lock() + defer b.mu.Unlock() + out := make([]string, len(b.lines)) + copy(out, b.lines) + return out +} + +// global log buffer for DNSTT logs. It is initialised when the server +// starts. Access via getDNSTTLogLines for concurrency safety. +var dnsttLogBuf *dnsttLogBuffer + +// getDNSTTLogLines returns the current DNSTT log lines in order. If the +// buffer has not been initialised, it returns an empty slice. +func getDNSTTLogLines() []string { + if dnsttLogBuf == nil { + return nil + } + return dnsttLogBuf.GetLines() +} + +// startDNSTT starts the integrated dnstt server if cfg is non-nil. It reads +// the Noise private key from cfg.PrivKeyFile, parses the configured DNSTT root +// domains into dns.Name values, and then launches runDNSTT in a goroutine. Any +// errors during start are logged. The SSH server configuration is used when +// handling streams. +func startDNSTT(cfg *DNSTTConfig, sshConf *ssh.ServerConfig) error { + if cfg == nil { + return nil + } + stopDNSTTAutoRestart() + if err := startDNSTTInstance(cfg, sshConf); err != nil { + return err + } + startDNSTTAutoRestart(cfg, sshConf) + return nil +} + +func startDNSTTInstance(cfg *DNSTTConfig, sshConf *ssh.ServerConfig) error { + if cfg == nil { + return nil + } + startDNSTTCapReaper() + dnsttSSHConfig = sshConf + // Configure whether periodic DNSTT statistics should be emitted to stderr. + // When DisableStatsLog is true, stats will be collected but log lines are suppressed. + dnsttPrintStats = !cfg.DisableStatsLog + dnsttLogConnections.Store(cfg.LogConnections) + limits := dnsttLimitsFromConfig(cfg) + // Initialise the log buffer once. Use a capacity of 100 lines (~few KB). + if dnsttLogBuf == nil { + dnsttLogBuf = newDNSTTLogBuffer(100) + } + // Configure the DNSTT logger output. If DisableConsoleLog is set, + // write only to the buffer; otherwise tee to both the buffer and stderr. + if cfg.DisableConsoleLog { + dnsttLog.SetOutput(dnsttLogBuf) + } else { + dnsttLog.SetOutput(io.MultiWriter(dnsttLogBuf, os.Stderr)) + } + + // Read the private key from file. + f, err := os.Open(cfg.PrivKeyFile) + if err != nil { + msg := fmt.Errorf("cannot open privkey file %s: %w", cfg.PrivKeyFile, err) + dnsttLog.Print(msg.Error()) + return msg + } + privkey, err := noise.ReadKey(f) + f.Close() + if err != nil { + msg := fmt.Errorf("cannot read privkey from file: %w", err) + dnsttLog.Print(msg.Error()) + return msg + } + // Parse the accepted DNS root domains. dns.ParseName accepts a domain with a + // trailing dot or without. Any invalid value aborts the dnstt server so a bad + // local/test domain does not silently create a broken listener. + domainStrings := normalizeDNSTTDomainList(cfg.Domain, cfg.Domains) + if cfg.FakeDNSEnabled { + cfg.FakeDNSListen = strings.TrimSpace(cfg.FakeDNSListen) + if cfg.FakeDNSListen == "" { + cfg.FakeDNSListen = "[::]:53" + } + cfg.FakeDNSDomain = strings.TrimSpace(cfg.FakeDNSDomain) + if cfg.FakeDNSDomain == "" { + cfg.FakeDNSDomain = "t.local.lan" + } + // Include the local/fake zone in the normal domain list too, so the same + // server accepts that test domain from either listener if needed. + domainStrings = normalizeDNSTTDomainList(cfg.Domain, append(cfg.Domains, cfg.FakeDNSDomain)) + } + if len(domainStrings) == 0 { + msg := fmt.Errorf("dnstt: at least one domain is required") + dnsttLog.Print(msg.Error()) + return msg + } + cfg.Domain = domainStrings[0] + cfg.Domains = domainStrings + domains, err := parseDNSTTDomains(domainStrings) + if err != nil { + dnsttLog.Print(err.Error()) + return err + } + + udpListen, _ := normalizeDNSTTListenDefault(cfg.UDPListen) + cfg.UDPListen = udpListen + + fakeDomains := domains + if cfg.FakeDNSEnabled { + localDomains := normalizeDNSTTDomainList(cfg.FakeDNSDomain, nil) + if len(localDomains) == 0 { + localDomains = []string{"t.local.lan"} + cfg.FakeDNSDomain = localDomains[0] + } + fakeDomains, err = parseDNSTTDomains(localDomains) + if err != nil { + dnsttLog.Print(err.Error()) + return err + } + } + + // Bind synchronously so the admin panel can immediately know whether DNSTT + // really started or failed because of a bad address/locked port. + listeners := []dnsttListenerSpec{} + mainConn, err := listenDNSTTPacket(udpListen) + if err != nil { + msg := fmt.Errorf("dnstt: opening UDP listener on %s: %w", udpListen, err) + dnsttLog.Print(msg.Error()) + return msg + } + listeners = append(listeners, dnsttListenerSpec{Label: "dnstt", Listen: udpListen, Conn: mainConn, Domains: domains}) + if cfg.FakeDNSEnabled { + if sameUDPListenAddress(cfg.FakeDNSListen, udpListen) { + dnsttLog.Printf("built-in local DNS listener shares main DNSTT address %q; using main listener", udpListen) + } else { + fakeConn, err := listenDNSTTPacket(cfg.FakeDNSListen) + if err != nil { + _ = closeDNSTTListenerSpecs(listeners) + msg := fmt.Errorf("dnstt: opening built-in local DNS listener on %s: %w", cfg.FakeDNSListen, err) + dnsttLog.Print(msg.Error()) + return msg + } + listeners = append(listeners, dnsttListenerSpec{Label: "local-dns", Listen: cfg.FakeDNSListen, Conn: fakeConn, Domains: fakeDomains}) + } + } + + // Log initialisation parameters so DNSTT startup is visible even when + // quiet logging is enabled. This helps with debugging. + dnsttLog.Printf("starting: domains=%q udp_listen=%q fake_dns_enabled=%v fake_dns_listen=%q fake_dns_domain=%q privkey=%q max_sessions=%d max_streams=%d pending_responses=%d stream_buffer=%d udp_rbuf=%d udp_wbuf=%d fake_dns_workers=%d dns_response_workers=%d log_connections=%v", domainStrings, udpListen, cfg.FakeDNSEnabled, cfg.FakeDNSListen, cfg.FakeDNSDomain, cfg.PrivKeyFile, limits.MaxSessions, limits.MaxStreams, limits.PendingResponses, limits.StreamBuffer, limits.UDPReadBuffer, limits.UDPWriteBuffer, limits.FakeDNSWorkers, limits.DNSResponseWorkers, dnsttLogConnections.Load()) + go func() { + defer dnsttRecover("runDNSTTOnListeners") + if err := runDNSTTOnListeners(privkey, listeners, limits); err != nil && !errors.Is(err, net.ErrClosed) { + dnsttLog.Printf("server exited with error: %v", err) + } + }() + return nil +} + +func parseDNSTTDomains(domainStrings []string) ([]dns.Name, error) { + domains := make([]dns.Name, 0, len(domainStrings)) + for _, raw := range domainStrings { + domain, err := dns.ParseName(raw) + if err != nil { + return nil, fmt.Errorf("invalid DNSTT domain %q: %w", raw, err) + } + domains = append(domains, domain) + } + // Match the most specific suffix first. This prevents a broad root like + // example.com from stealing queries that should be handled by t.example.com. + sort.SliceStable(domains, func(i, j int) bool { + return len(domains[i]) > len(domains[j]) + }) + return domains, nil +} + +// dnsttListenerSpec describes one UDP DNS socket feeding the same DNSTT/KCP +// session pool. The normal listener may accept all configured domains, while +// the built-in local/fake DNS listener can be restricted to one test zone such +// as t.local.lan. +type dnsttListenerSpec struct { + Label string + Listen string + Conn net.PacketConn + Domains []dns.Name +} + +func closeDNSTTListenerSpecs(listeners []dnsttListenerSpec) error { + var first error + for _, l := range listeners { + if l.Conn == nil { + continue + } + if err := l.Conn.Close(); err != nil && first == nil { + first = err + } + } + return first +} + +func listenDNSTTPacket(addr string) (net.PacketConn, error) { + network := "udp" + if host, _, err := net.SplitHostPort(addr); err == nil { + host = strings.Trim(host, "[]") + if ip := net.ParseIP(host); ip != nil { + if ip.To4() == nil { + // Important for the user's IPv6-only test case: udp6 avoids trying to + // reserve IPv4 port 53 when another DNS server already owns IPv4. + network = "udp6" + } else { + network = "udp4" + } + } + } + return net.ListenPacket(network, addr) +} + +func sameUDPListenAddress(a, b string) bool { + a = strings.TrimSpace(a) + b = strings.TrimSpace(b) + if a == "" || b == "" { + return false + } + return strings.EqualFold(a, b) +} + +func startDNSTTAutoRestart(cfg *DNSTTConfig, sshConf *ssh.ServerConfig) { + interval := dnsttAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := dnsttAutoRestartGrace(cfg) + cfgCopy := *cfg + ctx, cancel := context.WithCancel(context.Background()) + dnsttAutoMu.Lock() + if dnsttAutoCancel != nil { + dnsttAutoCancel() + } + dnsttAutoCancel = cancel + dnsttAutoMu.Unlock() + + go func() { + t := time.NewTicker(interval) + defer t.Stop() + dnsttLog.Printf("auto restart enabled: interval=%s grace=%s", interval, grace) + for { + select { + case <-ctx.Done(): + return + case <-t.C: + dnsttLog.Printf("auto restart: cycling DNSTT listener") + stopDNSTTListener() + select { + case <-ctx.Done(): + return + case <-time.After(grace): + } + for attempt := 1; ; attempt++ { + if err := startDNSTTInstance(&cfgCopy, sshConf); err != nil { + dnsttLog.Printf("auto restart: start attempt %d failed: %v", attempt, err) + select { + case <-ctx.Done(): + return + case <-time.After(10 * time.Second): + } + continue + } + dnsttLog.Printf("auto restart: DNSTT listener restarted") + break + } + } + } + }() +} + +func dnsttAutoRestartInterval(cfg *DNSTTConfig) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.AutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + dnsttLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err) + return 0 + } + if d < time.Minute { + dnsttLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw) + return 0 + } + return d +} + +func dnsttAutoRestartGrace(cfg *DNSTTConfig) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace)) + if err != nil || d < 0 { + dnsttLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace) + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +func dnsttRunning() bool { + dnsttConnMu.Lock() + defer dnsttConnMu.Unlock() + return len(dnsttConns) > 0 +} + +// handleDNSTTStream accepts a smux.Stream from a client and hands it off to +// handleConn. The stream is wrapped as a net.Conn by streamConn so that +// handleConn sees a minimal net.Conn interface. This function blocks until +// handleConn returns, then returns nil. Any errors from handleConn are +// ignored; they are logged by handleConn itself. +func handleDNSTTStream(stream *smux.Stream, conv uint32) error { + // Assign a per-stream sequence number to help correlate open/close events. + sid := atomic.AddUint64(&dnsttStats.StreamSeq, 1) + start := time.Now() + if dnsttLogConnections.Load() { + dnsttLog.Printf("ssh stream begin: conv=%d sid=%d", conv, sid) + } + sc := &streamConn{Stream: stream} + // Delegate to the existing SSH connection handler. This call blocks + // until the SSH connection terminates. The smux stream will be closed + // by handleConn when it returns. + handleConn(sc, dnsttSSHConfig) + if dnsttLogConnections.Load() { + dnsttLog.Printf("ssh stream end: conv=%d sid=%d duration=%s", conv, sid, time.Since(start)) + } + return nil +} + +// streamConn adapts a smux.Stream to the net.Conn interface expected by +// handleConn. smux.Stream implements Read, Write, and (via its embedded +// *stream) real deadline methods, but its addresses reflect the underlying +// KCP/Noise DummyAddr, so we only override LocalAddr/RemoteAddr with a stable +// "dnstt" placeholder for logging. The deadline methods are intentionally NOT +// overridden: handleConn's sshHandshakeTimeout guard relies on SetReadDeadline +// actually working, otherwise a stream that opens but never completes the SSH +// handshake wedges a goroutine until MaxStreams is hit. +type streamConn struct { + *smux.Stream +} + +func (s *streamConn) LocalAddr() net.Addr { return dummyAddr{} } +func (s *streamConn) RemoteAddr() net.Addr { return dummyAddr{} } + +// dummyAddr is a stand‑in net.Addr implementation for dnstt streams. It +// reports a generic network and address; this satisfies the net.Conn +// interface. handleConn logs the remote address, but here we provide +// "dnstt" as both network and address to indicate a tunnelled connection. +type dummyAddr struct{} + +func (d dummyAddr) Network() string { return "dnstt" } +func (d dummyAddr) String() string { return "dnstt" } + +// acceptDNSTTStreams wraps a KCP session in a Noise channel and an smux +// Session, then waits for smux streams. Each stream is passed to +// handleDNSTTStream. Any errors from the Noise or smux layers are returned. +func acceptDNSTTStreams(conn *kcp.UDPSession, privkey []byte, limits dnsttRuntimeLimits) error { + // Bound the Noise handshake read. A client can complete the KCP accept and + // then go silent (UDP: no FIN) before sending the Noise handshake; with no + // deadline, noise.NewServer's blocking ReadFull would park this goroutine + // and its KCP session forever (nothing frees them — smux keepalive cannot + // help because smux is not constructed until after the handshake). idleTimeout + // is generous: a real client sends the handshake immediately after connecting. + _ = conn.SetReadDeadline(time.Now().Add(idleTimeout)) + // Put a Noise channel on top of the KCP conn. + rw, err := noise.NewServer(conn, privkey) + if err != nil { + return err + } + // Clear the handshake deadline; the live session is governed by smux + // KeepAliveTimeout and KCP's own dead-link detection from here on. + _ = conn.SetReadDeadline(time.Time{}) + + // Put an smux session on top of the encrypted Noise channel. + smuxConfig := smux.DefaultConfig() + smuxConfig.Version = 2 + smuxConfig.KeepAliveTimeout = idleTimeout + if limits.StreamBuffer > 0 { + smuxConfig.MaxStreamBuffer = limits.StreamBuffer + } + sess, err := smux.Server(rw, smuxConfig) + if err != nil { + return err + } + defer sess.Close() + + for { + stream, err := sess.AcceptStream() + if err != nil { + if err, ok := err.(net.Error); ok && err.Temporary() { + continue + } + return err + } + if limits.MaxStreams > 0 && atomic.LoadInt64(&dnsttActiveStreams) >= int64(limits.MaxStreams) { + rej := atomic.AddUint64(&dnsttStats.StreamRejected, 1) + dnsttLogDropEvery(rej, "rejecting DNSTT stream: active_streams=%d max_streams=%d rejected=%d", atomic.LoadInt64(&dnsttActiveStreams), limits.MaxStreams, rej) + _ = stream.Close() + continue + } + atomic.AddInt64(&dnsttActiveStreams, 1) + atomic.AddUint64(&dnsttStats.SmuxStreamsNew, 1) + if dnsttLogConnections.Load() { + dnsttLog.Printf("new smux stream: conv=%d", conn.GetConv()) + } + // For each new smux stream, hand it off to our SSH handler. + go func(s *smux.Stream, conv uint32) { + defer dnsttRecover("smux stream") + defer atomic.AddInt64(&dnsttActiveStreams, -1) + defer atomic.AddUint64(&dnsttStats.SmuxStreamsEnd, 1) + defer s.Close() + _ = handleDNSTTStream(s, conv) + if dnsttLogConnections.Load() { + dnsttLog.Printf("smux stream closed: conv=%d", conv) + } + }(stream, conn.GetConv()) + } +} + +// acceptDNSTTSessions listens for incoming KCP connections and passes them to +// acceptDNSTTStreams. It configures window sizes and MTU on each accepted +// session as in the original dnstt-server. +func acceptDNSTTSessions(ln *kcp.Listener, privkey []byte, mtu int, limits dnsttRuntimeLimits) error { + for { + conn, err := ln.AcceptKCP() + if err != nil { + if err, ok := err.(net.Error); ok && err.Temporary() { + continue + } + return err + } + from := conn.RemoteAddr().String() + // Choose a per-session MTU derived from the inferred/advertised UDP payload + // capability for this client. This is essential on paths that clamp UDP + // payloads below our global cap (e.g. ~930), because KCP packets larger than + // what can fit in a single DNS response will cause the tunnel to stall. + effectiveLimit := maxUDPPayload + if v, ok := dnsttClientPayloadCap.Load(from); ok { + effectiveLimit = v.(clientCapEntry).Cap + if effectiveLimit < 512 { + effectiveLimit = 512 + } + if effectiveLimit > maxUDPPayload { + effectiveLimit = maxUDPPayload + } + } + maxEnc := cachedMaxEncodedPayload(effectiveLimit) + mtuSession := mtu + if maxEnc > 0 { + if m := maxEnc - 2; m >= 80 { + mtuSession = m + } + } + if limits.MaxSessions > 0 && atomic.LoadInt64(&dnsttActiveSessions) >= int64(limits.MaxSessions) { + rej := atomic.AddUint64(&dnsttStats.SessRejected, 1) + dnsttLogDropEvery(rej, "rejecting DNSTT session: active_sessions=%d max_sessions=%d rejected=%d", atomic.LoadInt64(&dnsttActiveSessions), limits.MaxSessions, rej) + _ = conn.Close() + continue + } + atomic.AddInt64(&dnsttActiveSessions, 1) + atomic.AddUint64(&dnsttStats.KCPSessionsNew, 1) + if dnsttLogConnections.Load() { + dnsttLog.Printf("new KCP session: conv=%d from=%s mtu=%d limit=%d", conn.GetConv(), from, mtuSession, effectiveLimit) + } + // Permit coalescing the payloads of consecutive sends. + conn.SetStreamMode(true) + // Disable the dynamic congestion window (limit only by the maximum of + // local and remote static windows). + conn.SetNoDelay(0, 0, 0, 1) + conn.SetWindowSize(turbotunnel.QueueSize/2, turbotunnel.QueueSize/2) + if rc := conn.SetMtu(mtuSession); !rc { + dnsttLog.Printf("rejecting DNSTT session: invalid mtu=%d conv=%d from=%s", mtuSession, conn.GetConv(), from) + atomic.AddInt64(&dnsttActiveSessions, -1) + _ = conn.Close() + continue + } + go func(c *kcp.UDPSession, conv uint32, from string) { + defer dnsttRecover("kcp session") + defer atomic.AddInt64(&dnsttActiveSessions, -1) + defer atomic.AddUint64(&dnsttStats.KCPSessionsEnd, 1) + defer c.Close() + err := acceptDNSTTStreams(c, privkey, limits) + if dnsttLogConnections.Load() { + if err != nil && err != io.ErrClosedPipe { + dnsttLog.Printf("kcp session closed: conv=%d from=%s err=%v", conv, from, err) + } else { + dnsttLog.Printf("kcp session closed: conv=%d from=%s", conv, from) + } + } + }(conn, conn.GetConv(), conn.RemoteAddr().String()) + } +} + +// record represents a DNS message appropriate for a response to a previously +// received query, along with metadata necessary for sending the response. +// recvLoop sends instances of record to sendLoop via a channel. sendLoop +// receives instances of record and may fill in the message's Answer section +// before sending it. +type record struct { + Resp *dns.Message + Conn net.PacketConn + Addr net.Addr + Listener string + ClientID turbotunnel.ClientID + // PayloadLimit holds the maximum UDP payload size advertised by the + // client via EDNS(0). sendLoop uses this to clamp outgoing DNS + // responses so they never exceed what the client claims it will + // accept. A zero value means no per-client limit and defaults to + // maxUDPPayload. + PayloadLimit int +} + +type recordSink interface { + Enqueue(*record) bool + Len() int + Cap() int + ShardCount() int + Shard(int) <-chan *record + Close() +} + +type shardedRecordSink struct { + chans []chan *record +} + +func newShardedRecordSink(totalCapacity, shards int) *shardedRecordSink { + if shards < 1 { + shards = 1 + } + if totalCapacity < shards { + totalCapacity = shards + } + perShard := totalCapacity / shards + if perShard < 1 { + perShard = 1 + } + extra := totalCapacity % shards + s := &shardedRecordSink{chans: make([]chan *record, shards)} + for i := range s.chans { + capForShard := perShard + if i < extra { + capForShard++ + } + s.chans[i] = make(chan *record, capForShard) + } + return s +} + +func (s *shardedRecordSink) Enqueue(rec *record) bool { + if s == nil || len(s.chans) == 0 { + return false + } + ch := s.chans[recordShardIndex(rec, len(s.chans))] + select { + case ch <- rec: + return true + default: + return false + } +} + +func (s *shardedRecordSink) Len() int { + if s == nil { + return 0 + } + n := 0 + for _, ch := range s.chans { + n += len(ch) + } + return n +} + +func (s *shardedRecordSink) Cap() int { + if s == nil { + return 0 + } + n := 0 + for _, ch := range s.chans { + n += cap(ch) + } + return n +} + +func (s *shardedRecordSink) ShardCount() int { + if s == nil { + return 0 + } + return len(s.chans) +} + +func (s *shardedRecordSink) Shard(i int) <-chan *record { + return s.chans[i] +} + +func (s *shardedRecordSink) Close() { + if s == nil { + return + } + for _, ch := range s.chans { + close(ch) + } +} + +func recordShardIndex(rec *record, shards int) int { + if shards <= 1 || rec == nil { + return 0 + } + var h uint32 = 2166136261 + allZeroClient := true + for _, b := range rec.ClientID { + if b != 0 { + allZeroClient = false + } + h ^= uint32(b) + h *= 16777619 + } + // Invalid/error responses often have an all-zero ClientID. Mix in the remote + // address so NXDOMAIN/FORMERR traffic is not forced onto one shard. + if allZeroClient && rec.Addr != nil { + addr := rec.Addr.String() + for i := 0; i < len(addr); i++ { + h ^= uint32(addr[i]) + h *= 16777619 + } + } + return int(h % uint32(shards)) +} + +// nextPacket reads the next length‑prefixed packet from r, ignoring padding. +// It returns a nil error only when a packet was read successfully. It +// returns io.EOF only when there were 0 bytes remaining to read from r. It +// returns io.ErrUnexpectedEOF when EOF occurs in the middle of an encoded +// packet. See dnstt-server/main.go for details. +func nextPacket(r *bytes.Reader) ([]byte, error) { + eof := func(err error) error { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return err + } + for { + prefix, err := r.ReadByte() + if err != nil { + // We may return a real io.EOF only here. + return nil, err + } + if prefix >= 224 { + paddingLen := prefix - 224 + _, err := io.CopyN(io.Discard, r, int64(paddingLen)) + if err != nil { + return nil, eof(err) + } + } else { + p := make([]byte, int(prefix)) + _, err = io.ReadFull(r, p) + return p, eof(err) + } + } +} + +// responseFor constructs a response dns.Message that is appropriate for query. +// Along with the dns.Message, it returns the query's decoded data payload. If +// the returned dns.Message is nil, it means that there should be no response +// to this query. If the returned dns.Message has an Rcode() of +// dns.RcodeNoError, the message is a candidate for carrying downstream data +// in a TXT record. This function is adapted from dnstt-server/main.go. +func responseFor(query *dns.Message, domain dns.Name) (*dns.Message, []byte) { + resp := &dns.Message{ + ID: query.ID, + Flags: 0x8000, // QR = 1, RCODE = no error + Question: query.Question, + } + if query.Flags&0x8000 != 0 { + // QR != 0, this is not a query. Don't even send a response. + return nil, nil + } + // Check for EDNS(0) support. Include our own OPT RR only if we receive + // one from the requester. + payloadSize := 0 + for _, rr := range query.Additional { + if rr.Type != dns.RRTypeOPT { + continue + } + version := (rr.TTL >> 16) & 0xff + if version != 0 { + resp.Flags |= dns.ExtendedRcodeBadVers & 0xf + additional := dns.RR{ + Name: dns.Name{}, + Type: dns.RRTypeOPT, + Class: 0, + TTL: (dns.ExtendedRcodeBadVers >> 4) << 24, + Data: []byte{}, + } + resp.Additional = append(resp.Additional, additional) + return resp, nil + } + payloadSize = int(rr.Class) + } + if payloadSize < 512 { + payloadSize = 512 + } + // There must be exactly one question. + if len(query.Question) != 1 { + resp.Flags |= dns.RcodeFormatError + dnsttLog.Printf("FORMERR: too few or too many questions (%d)", len(query.Question)) + return resp, nil + } + question := query.Question[0] + // Check the name to see if it ends in our chosen domain, and extract + // all that comes before the domain if it does. If it does not, we + // return RcodeNameError. + prefix, ok := question.Name.TrimSuffix(domain) + if !ok { + resp.Flags |= dns.RcodeNameError + // NXDOMAIN: not authoritative for this name + return resp, nil + } + resp.Flags |= 0x0400 // AA = 1 + if query.Opcode() != 0 { + resp.Flags |= dns.RcodeNotImplemented + return resp, nil + } + if question.Type != dns.RRTypeTXT { + // We only support QTYPE == TXT. + resp.Flags |= dns.RcodeNameError + return resp, nil + } + encoded := bytes.ToUpper(bytes.Join(prefix, nil)) + payload := make([]byte, base32Encoding.DecodedLen(len(encoded))) + n, err := base32Encoding.Decode(payload, encoded) + if err != nil { + resp.Flags |= dns.RcodeNameError + return resp, nil + } + payload = payload[:n] + // Do not reject queries advertising a smaller EDNS UDP payload than + // maxUDPPayload. We clamp responses to the client‑advertised size + // later in sendLoop. + return resp, payload +} + +// responseForDomains is like responseFor, but it accepts a query under any of +// the configured DNSTT root domains. This lets one UDP listener serve public +// and local/test NS domains at the same time while using the same KCP/noise +// session pool and private key. +func responseForDomains(query *dns.Message, domains []dns.Name) (*dns.Message, []byte) { + for i, domain := range domains { + resp, payload := responseFor(query, domain) + if resp == nil { + return nil, nil + } + if resp.Rcode() != dns.RcodeNameError || len(payload) > 0 { + return resp, payload + } + // Try the next configured domain only when this one did not match. Other + // NAMEERROR conditions (bad QTYPE, bad base32 payload, etc.) are terminal + // after the final domain. + if i == len(domains)-1 { + return resp, payload + } + } + return responseFor(query, dns.Name([][]byte{})) +} + +// recvLoop repeatedly calls dnsConn.ReadFrom, extracts the packets contained in +// the incoming DNS queries, and puts them on ttConn's incoming queue. +// Whenever a query calls for a response, constructs a partial response and +// passes it to sendLoop over ch. +func recvLoop(label string, domains []dns.Name, dnsConn net.PacketConn, ttConn *turbotunnel.QueuePacketConn, sink recordSink) error { + for { + var buf [4096]byte + n, addr, err := dnsConn.ReadFrom(buf[:]) + if err != nil { + if err, ok := err.(net.Error); ok && err.Temporary() { + dnsttLog.Printf("ReadFrom temporary error: %v", err) + continue + } + return err + } + atomic.AddUint64(&dnsttStats.DNSRx, 1) + // Parse DNS query. + query, err := dns.MessageFromWireFormat(buf[:n]) + if err != nil { + pe := atomic.AddUint64(&dnsttStats.DNSParseErr, 1) + dnsttLogDropEvery(pe, "cannot parse DNS query: %v", err) + continue + } + // Determine an effective UDP payload limit for this query. + // + // Prefer EDNS(0) if present. However, many resolver paths strip EDNS while + // still allowing UDP responses larger than 512. For those paths, infer a + // practical limit from the observed query size (if we received a ~900-byte + // query, the path clearly supports >512 UDP). Clamp to our global cap. + payloadLimit := 0 + hasEDNS := false + for _, rr := range query.Additional { + if rr.Type != dns.RRTypeOPT { + continue + } + hasEDNS = true + // The lower 16 bits of the Class field of the OPT RR specify the + // requestor's maximum UDP payload size (RFC 6891). + sz := int(rr.Class) + if sz < 512 { + sz = 512 + } + payloadLimit = sz + break + } + if !hasEDNS { + atomic.AddUint64(&dnsttStats.NoEDNS, 1) + payloadLimit = n + if payloadLimit < 512 { + payloadLimit = 512 + } + } else { + // If EDNS is present but appears to under-advertise the true path MTU, + // treat the observed query size as a lower bound. Some resolvers clamp or + // rewrite EDNS values even though they can carry larger UDP payloads. + if n > payloadLimit { + payloadLimit = n + } + } + // Many resolver paths do not include EDNS (or clamp it to 512) but still + // reliably carry larger UDP DNS messages (commonly ~900 bytes). For DNSTT + // this matters because downstream data rides in responses; treating such + // paths as strictly 512-byte causes the tunnel to stall. + // + // noEDNSFallbackPayload acts as a floor for these cases; if you want strict + // RFC 1035 behaviour, set it to 512. + if payloadLimit < noEDNSFallbackPayload { + payloadLimit = noEDNSFallbackPayload + } + if payloadLimit > maxUDPPayload { + payloadLimit = maxUDPPayload + } + if payloadLimit == 512 { + atomic.AddUint64(&dnsttStats.SmallEDNS, 1) + } + resp, payload := responseForDomains(&query, domains) + // Extract ClientID + var clientID turbotunnel.ClientID + n = copy(clientID[:], payload) + payload = payload[n:] + if n == len(clientID) { + // Update our per-client capability estimate so we can choose a suitable + // per-session KCP MTU even when EDNS is stripped. + updateClientPayloadCap(clientID, payloadLimit) + // Feed packets into KCP. + r := bytes.NewReader(payload) + for { + p, err := nextPacket(r) + if err != nil { + break + } + ttConn.QueueIncoming(p, clientID) + } + } else { + if resp != nil && resp.Rcode() == dns.RcodeNoError { + resp.Flags |= dns.RcodeNameError + } + } + if resp != nil { + // Push this record along with the per‑client payload limit to the sender. + rec := &record{ + Resp: resp, + Conn: dnsConn, + Addr: addr, + Listener: label, + ClientID: clientID, + PayloadLimit: payloadLimit, + } + if sink.Enqueue(rec) { + atomic.AddUint64(&dnsttStats.RecQueued, 1) + } else { + d := atomic.AddUint64(&dnsttStats.RecDropped, 1) + // Log occasionally to avoid flooding logs under sustained overload. + if d == 1 || d%1000 == 0 { + dnsttLog.Printf("dropping response record: ch_len=%d ch_cap=%d dropped=%d", sink.Len(), sink.Cap(), d) + } + } + } + } +} + +// sendLoop repeatedly receives records from ch. Those that represent an +// error response are sent immediately. Those that represent a response +// capable of carrying data are packed full of as many packets as will fit +// while keeping the total size under maxEncodedPayload, then sent. +func sendLoop(ttConn *turbotunnel.QueuePacketConn, ch <-chan *record, maxEncodedPayload int, done <-chan struct{}) error { + var nextRec *record + for { + rec := nextRec + nextRec = nil + if rec == nil { + var ok bool + select { + case <-done: + return nil + case rec, ok = <-ch: + if !ok { + return nil + } + } + } + // Determine the effective per-query UDP payload limit. + // + // rec.PayloadLimit comes from EDNS(0) and our heuristic floor/observations. + // Additionally, we maintain a per-client learned capability (dnsttClientPayloadCap) + // that can be promoted when we observe that larger downstream responses are + // needed and appear to be supported. Use the larger of the two, then clamp + // to our global cap. + effectivePayloadLimit := rec.PayloadLimit + if v, ok := dnsttClientPayloadCap.Load(dnsttClientKey(rec.ClientID)); ok { + if cap := v.(clientCapEntry).Cap; cap > effectivePayloadLimit { + effectivePayloadLimit = cap + } + } + if effectivePayloadLimit <= 0 { + effectivePayloadLimit = maxUDPPayload + } + if effectivePayloadLimit > maxUDPPayload { + effectivePayloadLimit = maxUDPPayload + } + // Compute a per-limit "max encoded payload" so we avoid generating a DNS + // response that would need truncation (TC). Truncation breaks DNSTT because + // resolvers retry over TCP, which we don't support here. + maxEnc := cachedMaxEncodedPayload(effectivePayloadLimit) + if maxEnc < 0 { + maxEnc = 0 + } + // Note: KCP MTU is set per session in acceptDNSTTSessions based on inferred + // per-client capability, so we do not warn here about MTU mismatches. + + if rec.Resp.Rcode() == dns.RcodeNoError && len(rec.Resp.Question) == 1 { + // It's a non-error response, so we can fill the Answer section. + rec.Resp.Answer = []dns.RR{{ + Name: rec.Resp.Question[0].Name, + Type: rec.Resp.Question[0].Type, + Class: rec.Resp.Question[0].Class, + TTL: responseTTL, + Data: nil, + }} + var payload bytes.Buffer + limit := maxEnc + timer := time.NewTimer(maxResponseDelay) + packets := 0 + for { + var p []byte + unstash := ttConn.Unstash(rec.ClientID) + outgoing := ttConn.OutgoingQueue(rec.ClientID) + select { + case p = <-unstash: + default: + select { + case p = <-unstash: + case p = <-outgoing: + default: + select { + case p = <-unstash: + case p = <-outgoing: + case <-timer.C: + case nextRec = <-ch: + case <-done: + timer.Stop() + return nil + } + } + } + timer.Reset(0) + if len(p) == 0 { + break + } + limit -= 2 + len(p) + // Never exceed the per-query maximum encoded payload. If the next packet + // would overflow, stash it for the next response (even if this would have + // been the first packet). + if limit < 0 { + ttConn.Stash(p, rec.ClientID) + break + } + binary.Write(&payload, binary.BigEndian, uint16(len(p))) + payload.Write(p) + packets++ + } + timer.Stop() + rec.Resp.Answer[0].Data = dns.EncodeRDataTXT(payload.Bytes()) + if packets == 0 { + atomic.AddUint64(&dnsttStats.RespEmpty, 1) + } else { + atomic.AddUint64(&dnsttStats.RespWithData, 1) + } + } + buf, err := rec.Resp.WireFormat() + if err != nil { + dnsttLog.Printf("resp WireFormat: %v", err) + continue + } + if len(buf) > effectivePayloadLimit { + // The resolver may under-advertise (or omit) its UDP payload limit while + // still accepting larger UDP responses. Rather than dropping downstream + // data (which can stall DNSTT), treat this as a hint and promote the + // per-client inferred payload capability. + atomic.AddUint64(&dnsttStats.RespOversize, 1) + promoteTo := len(buf) + if promoteTo > maxUDPPayload { + dnsttLog.Printf("oversize DNS response: size=%d limit=%d cap=%d (dropping)", len(buf), effectivePayloadLimit, maxUDPPayload) + continue + } + updateClientPayloadCap(rec.ClientID, promoteTo) + dnsttLog.Printf("oversize DNS response: size=%d limit=%d -> promote client to %d", len(buf), effectivePayloadLimit, promoteTo) + // After promotion, allow this response to be sent. + effectivePayloadLimit = promoteTo + } + if rec.Conn == nil { + dnsttLog.Printf("cannot send DNS response: missing listener for %s", rec.Listener) + continue + } + _, err = rec.Conn.WriteTo(buf, rec.Addr) + if err != nil { + if err, ok := err.(net.Error); ok && err.Temporary() { + dnsttLog.Printf("WriteTo temporary error: %v", err) + continue + } + return err + } + atomic.AddUint64(&dnsttStats.RespSent, 1) + atomic.AddUint64(&dnsttStats.RespSentBytes, uint64(len(buf))) + } +} + +// computeMaxEncodedPayload computes the maximum amount of downstream TXT RR +// data that keep the overall response size less than maxUDPPayload, in the +// worst case when the response answers a query that has a maximum-length name +// in its Question section. Returns 0 in the case that no amount of data +// makes the overall response size small enough. +func computeMaxEncodedPayload(limit int) int { + maxLengthName, err := dns.NewName([][]byte{ + []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), + []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), + []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), + []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), + }) + if err != nil { + panic(err) + } + { + n := 0 + for _, label := range maxLengthName { + n += len(label) + 1 + } + n += 1 + if n != 255 { + panic(fmt.Sprintf("dnstt: max-length name is %d octets, should be %d", n, 255)) + } + } + queryLimit := uint16(limit) + if int(queryLimit) != limit { + queryLimit = 0xffff + } + query := &dns.Message{ + Question: []dns.Question{{ + Name: maxLengthName, + Type: dns.RRTypeTXT, + Class: dns.RRTypeTXT, + }}, + Additional: []dns.RR{{ + Name: dns.Name{}, + Type: dns.RRTypeOPT, + Class: uint16(queryLimit), + TTL: 0, + Data: []byte{}, + }}, + } + resp, _ := responseFor(query, dns.Name([][]byte{})) + resp.Answer = []dns.RR{{ + Name: query.Question[0].Name, + Type: query.Question[0].Type, + Class: query.Question[0].Class, + TTL: responseTTL, + Data: nil, + }} + low := 0 + high := 32768 + for low+1 < high { + mid := (low + high) / 2 + resp.Answer[0].Data = dns.EncodeRDataTXT(make([]byte, mid)) + buf, err := resp.WireFormat() + if err != nil { + panic(err) + } + if len(buf) <= limit { + low = mid + } else { + high = mid + } + } + return low +} + +// runDNSTT starts a dnstt server on udpListen. It computes the effective +// MTU based on the configured maxUDPPayload, then accepts KCP sessions and +// handles DNS queries. Errors are returned only for fatal conditions. +func runDNSTT(privkey []byte, domain dns.Name, udpListen string) error { + dnsConn, err := listenDNSTTPacket(udpListen) + if err != nil { + return fmt.Errorf("dnstt: opening UDP listener on %s: %v", udpListen, err) + } + return runDNSTTOnListeners(privkey, []dnsttListenerSpec{{Label: "dnstt", Listen: udpListen, Conn: dnsConn, Domains: []dns.Name{domain}}}, dnsttLimitsFromConfig(nil)) +} + +func runDNSTTOnListeners(privkey []byte, listeners []dnsttListenerSpec, limits dnsttRuntimeLimits) error { + if len(listeners) == 0 { + return fmt.Errorf("dnstt: no UDP listeners configured") + } + done := make(chan struct{}) + defer close(done) + defer closeDNSTTListenerSpecs(listeners) + + registered := make([]net.PacketConn, 0, len(listeners)) + for _, l := range listeners { + if l.Conn == nil { + continue + } + if udp, ok := l.Conn.(*net.UDPConn); ok { + if limits.UDPReadBuffer > 0 { + _ = udp.SetReadBuffer(limits.UDPReadBuffer) + } + if limits.UDPWriteBuffer > 0 { + _ = udp.SetWriteBuffer(limits.UDPWriteBuffer) + } + } + registered = append(registered, l.Conn) + } + + // Register so stopDNSTT() can close every socket and unblock all read loops. + dnsttConnMu.Lock() + for _, c := range dnsttConns { + if c != nil { + _ = c.Close() + } + } + dnsttConns = registered + dnsttConnMu.Unlock() + defer func() { + dnsttConnMu.Lock() + // Only clear the global list if it still points at this generation. + if len(dnsttConns) == len(registered) { + same := true + for i := range registered { + if dnsttConns[i] != registered[i] { + same = false + break + } + } + if same { + dnsttConns = nil + } + } + dnsttConnMu.Unlock() + }() + + for _, l := range listeners { + dnsttLog.Printf("udp listener ready on %s (%s, domains=%q)", l.Listen, l.Label, dnsNamesForLog(l.Domains)) + } + // compute maximum encoded payload and resulting MTU + maxEncodedPayload := computeMaxEncodedPayload(maxUDPPayload) + mtu := maxEncodedPayload - 2 + if mtu < 80 { + if mtu < 0 { + mtu = 0 + } + return fmt.Errorf("dnstt: computed MTU %d too small", mtu) + } + // set up turbotunnel and KCP listener + ttConn := turbotunnel.NewQueuePacketConn(turbotunnel.DummyAddr{}, idleTimeout*2) + // Close ttConn on exit so its RemoteMap expiry goroutine is stopped. Without + // this, every DNSTT restart (hot-reload / auto-restart) leaks that goroutine + // plus the QueuePacketConn's buffers for the process lifetime. + defer ttConn.Close() + ln, err := kcp.ServeConn(nil, 0, 0, ttConn) + if err != nil { + return fmt.Errorf("dnstt: opening KCP listener: %v", err) + } + defer ln.Close() + go func() { + defer dnsttRecover("acceptDNSTTSessions") + if err := acceptDNSTTSessions(ln, privkey, mtu, limits); err != nil { + dnsttLog.Printf("acceptSessions error: %v", err) + } + }() + // NOTE: This channel buffers pending DNS response records. Keeping this + // extremely large can look like a "memory leak" under bursty load because + // records (and their associated allocations) are retained until drained. + // Keep it bounded so overload drops DNS responses instead of exhausting RAM. + pendingResponses := limits.PendingResponses + if pendingResponses <= 0 { + pendingResponses = defaultDNSTTPendingResponses + } + sink := newShardedRecordSink(pendingResponses, limits.DNSResponseWorkers) + // Periodically aggregate DNSTT counters. This goroutine runs every 5 seconds, + // resetting the atomic counters, storing them in lastDnsttStats and optionally + // emitting a log line. Even when dnsttPrintStats is false, statistics will + // still be collected and made available via the admin API. + go func() { + t := time.NewTicker(5 * time.Second) + defer t.Stop() + for { + select { + case <-done: + return + case <-t.C: + } + + dnsRx := atomic.SwapUint64(&dnsttStats.DNSRx, 0) + parseErr := atomic.SwapUint64(&dnsttStats.DNSParseErr, 0) + noEDNS := atomic.SwapUint64(&dnsttStats.NoEDNS, 0) + limit512 := atomic.SwapUint64(&dnsttStats.SmallEDNS, 0) + queued := atomic.SwapUint64(&dnsttStats.RecQueued, 0) + dropped := atomic.SwapUint64(&dnsttStats.RecDropped, 0) + respSent := atomic.SwapUint64(&dnsttStats.RespSent, 0) + respBytes := atomic.SwapUint64(&dnsttStats.RespSentBytes, 0) + respEmpty := atomic.SwapUint64(&dnsttStats.RespEmpty, 0) + respData := atomic.SwapUint64(&dnsttStats.RespWithData, 0) + over := atomic.SwapUint64(&dnsttStats.RespOversize, 0) + kcpNew := atomic.SwapUint64(&dnsttStats.KCPSessionsNew, 0) + kcpEnd := atomic.SwapUint64(&dnsttStats.KCPSessionsEnd, 0) + smuxNew := atomic.SwapUint64(&dnsttStats.SmuxStreamsNew, 0) + smuxEnd := atomic.SwapUint64(&dnsttStats.SmuxStreamsEnd, 0) + sessRejected := atomic.SwapUint64(&dnsttStats.SessRejected, 0) + streamRejected := atomic.SwapUint64(&dnsttStats.StreamRejected, 0) + panicRecovered := atomic.SwapUint64(&dnsttStats.PanicRecovered, 0) + // Update the snapshot + dnsttStatsMu.Lock() + lastDnsttStats = DnsttStatsSnapshot{ + Timestamp: time.Now(), + Running: dnsttRunning(), + DNSRx: dnsRx, + ParseErr: parseErr, + NoEDNS: noEDNS, + Limit512: limit512, + RecQueued: queued, + RecDropped: dropped, + RespSent: respSent, + RespBytes: respBytes, + RespEmpty: respEmpty, + RespData: respData, + RespOversize: over, + KCPNew: kcpNew, + KCPEnd: kcpEnd, + SmuxNew: smuxNew, + SmuxEnd: smuxEnd, + SessRejected: sessRejected, + StreamRejected: streamRejected, + PanicRecovered: panicRecovered, + ActiveSessions: atomic.LoadInt64(&dnsttActiveSessions), + ActiveStreams: atomic.LoadInt64(&dnsttActiveStreams), + ChLen: sink.Len(), + FakeDNSWorkers: limits.FakeDNSWorkers, + DNSResponseWorkers: limits.DNSResponseWorkers, + } + dnsttStatsMu.Unlock() + // Optionally log the snapshot to stderr + if dnsttPrintStats { + dnsttLog.Printf( + "stats 5s: dns_rx=%d parse_err=%d no_edns=%d limit512=%d rec_queued=%d rec_dropped=%d resp_sent=%d resp_bytes=%d resp_empty=%d resp_data=%d resp_oversize=%d kcp_new=%d kcp_end=%d smux_new=%d smux_end=%d sess_rejected=%d stream_rejected=%d panic_recovered=%d active_sessions=%d active_streams=%d ch_len=%d fake_dns_workers=%d response_workers=%d", + dnsRx, parseErr, noEDNS, limit512, queued, dropped, respSent, respBytes, respEmpty, respData, over, kcpNew, kcpEnd, smuxNew, smuxEnd, sessRejected, streamRejected, panicRecovered, atomic.LoadInt64(&dnsttActiveSessions), atomic.LoadInt64(&dnsttActiveStreams), sink.Len(), limits.FakeDNSWorkers, limits.DNSResponseWorkers, + ) + } + } + }() + for i := 0; i < sink.ShardCount(); i++ { + shard := i + go func() { + defer dnsttRecover(fmt.Sprintf("sendLoop-%d", shard+1)) + if err := sendLoop(ttConn, sink.Shard(shard), maxEncodedPayload, done); err != nil { + dnsttLog.Printf("sendLoop-%d error: %v", shard+1, err) + closeDNSTTListenerSpecs(listeners) + } + }() + } + + readWorkers := 0 + for _, l := range listeners { + if l.Label == "local-dns" && limits.FakeDNSWorkers > 1 { + readWorkers += limits.FakeDNSWorkers + } else { + readWorkers++ + } + } + errCh := make(chan error, readWorkers) + for _, l := range listeners { + listener := l + workers := 1 + if listener.Label == "local-dns" && limits.FakeDNSWorkers > 1 { + workers = limits.FakeDNSWorkers + } + for worker := 0; worker < workers; worker++ { + workerLabel := listener.Label + if workers > 1 { + workerLabel = fmt.Sprintf("%s-%d", listener.Label, worker+1) + } + domains := listener.Domains + conn := listener.Conn + go func(label string, domains []dns.Name, conn net.PacketConn) { + defer dnsttRecover("recvLoop " + label) + errCh <- recvLoop(label, domains, conn, ttConn, sink) + }(workerLabel, domains, conn) + } + } + err = <-errCh + closeDNSTTListenerSpecs(listeners) + return err +} + +func dnsNamesForLog(domains []dns.Name) []string { + out := make([]string, 0, len(domains)) + for _, d := range domains { + parts := make([]string, 0, len(d)) + for _, label := range d { + parts = append(parts, string(label)) + } + out = append(out, strings.Join(parts, ".")) + } + return out +} + +// ---- Key management API handlers ---- + +const dnsttKeyFile = "/opt/sshpanel/dnstt.key" + +// handleDnsttGenKey generates a new Noise keypair, saves the private key to +// dnsttKeyFile, and returns the hex-encoded public key. +func handleDnsttGenKey(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + privkey, err := noise.GeneratePrivkey() + if err != nil { + http.Error(w, "keygen: "+err.Error(), http.StatusInternalServerError) + return + } + f, err := os.OpenFile(dnsttKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError) + return + } + if err := noise.WriteKey(f, privkey); err != nil { + f.Close() + http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError) + return + } + f.Close() + pubkey := noise.PubkeyFromPrivkey(privkey) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "privkey_file": dnsttKeyFile, + "pubkey": noise.EncodeKey(pubkey), + }) +} + +// handleDnsttGetPubKey reads the configured private key and returns the +// corresponding public key so the admin can share it with dnstt clients. +func handleDnsttGetPubKey(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + cfg := getGlobalCfg() + keyPath := dnsttKeyFile + if cfg != nil && cfg.DNSTT != nil && cfg.DNSTT.PrivKeyFile != "" { + keyPath = cfg.DNSTT.PrivKeyFile + } + f, err := os.Open(keyPath) + if err != nil { + http.Error(w, "open key: "+err.Error(), http.StatusInternalServerError) + return + } + defer f.Close() + privkey, err := noise.ReadKey(f) + if err != nil { + http.Error(w, "read key: "+err.Error(), http.StatusInternalServerError) + return + } + pubkey := noise.PubkeyFromPrivkey(privkey) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "pubkey": noise.EncodeKey(pubkey), + }) +} diff --git a/dragoncore_cli.py b/dragoncore_cli.py new file mode 100644 index 0000000..8cc6e28 --- /dev/null +++ b/dragoncore_cli.py @@ -0,0 +1,947 @@ +#!/usr/bin/env python3 +"""DragonCoreSSH terminal administration. Python 3 standard library only. + +Root access to /opt/sshpanel/.env acts as local administrator authentication. +Passwords are generated; no password input or interactive login is requested. +""" + +import argparse +import datetime as dt +import json +import os +from pathlib import Path +import secrets +import shlex +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + + +INSTALL_DIR = Path(os.environ.get("DRAGONCORE_DIR", "/opt/sshpanel")) +ENV_FILE = INSTALL_DIR / ".env" +SERVICE = os.environ.get("DRAGONCORE_SERVICE", "sshpanel") + + +class CLIError(Exception): + pass + + +def require_root(): + if os.geteuid() != 0: + raise CLIError("Run from a root shell (or use sudo menu).") + + +def read_env(): + try: + fd = os.open(ENV_FILE, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(fd, encoding="utf-8") as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + raise CLIError(".env must be a regular file") + lines = handle.readlines() + except OSError as exc: + raise CLIError(f"Cannot read {ENV_FILE}: {exc}") from exc + values = {} + for line in lines: + if "=" in line and not line.lstrip().startswith("#"): + key, value = line.rstrip("\n").split("=", 1) + values[key.strip()] = value.strip().strip('"') + return lines, values + + +def api_password(): + token = read_env()[1].get("ADMIN_TOKEN", "") + if len(token) < 32: + raise CLIError("ADMIN_TOKEN is missing or too short in .env") + return token + + +def api_base(): + address = read_env()[1].get("ADMIN_HTTP_ADDR", "127.0.0.1:9090") + try: + parsed = urllib.parse.urlsplit("http://" + address) + port = parsed.port + if not port or not 1 <= port <= 65535: + raise ValueError("invalid port") + except ValueError as exc: + raise CLIError(f"Invalid ADMIN_HTTP_ADDR: {exc}") from exc + # Always connect locally, including when the API is explicitly exposed + # for managed-server integrations. + host = "[::1]" if parsed.hostname in ("::", "::1") else "127.0.0.1" + return f"http://{host}:{port}" + + +def request(method, path, data=None, timeout=25): + if not path.startswith("/") or path.startswith("//"): + raise CLIError("Invalid API path") + body = None if data is None else json.dumps(data).encode("utf-8") + req = urllib.request.Request( + api_base() + path, data=body, method=method, + headers={"Authorization": "Bearer " + api_password(), + "Content-Type": "application/json", "Accept": "application/json"}, + ) + try: + # Do not send the bearer credential through an inherited HTTP proxy. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=timeout) as response: + raw = response.read(2 * 1024 * 1024) + return json.loads(raw) if raw.strip() else None + except urllib.error.HTTPError as exc: + detail = exc.read(2048).decode("utf-8", "replace").strip() + raise CLIError(f"API {exc.code}: {detail}") from exc + except (urllib.error.URLError, TimeoutError) as exc: + raise CLIError(f"API unavailable at {api_base()}: {exc}") from exc + + +def write_env_token(token): + if len(token) < 32 or not all(ch.isalnum() or ch in "-_" for ch in token): + raise CLIError("API password must have 32+ letters, digits, - or _") + lines, _ = read_env() + replaced = False + out = [] + for line in lines: + if line.startswith("ADMIN_TOKEN="): + if not replaced: + out.append("ADMIN_TOKEN=" + token + "\n") + replaced = True + else: + out.append(line) + if not replaced: + out.append("ADMIN_TOKEN=" + token + "\n") + old = os.stat(ENV_FILE, follow_symlinks=False) + fd, tmp = tempfile.mkstemp(prefix=".env.dragoncore-", dir=ENV_FILE.parent) + try: + os.fchmod(fd, 0o600) + os.fchown(fd, old.st_uid, old.st_gid) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.writelines(out) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp, ENV_FILE) + dirfd = os.open(ENV_FILE.parent, os.O_RDONLY) + try: + os.fsync(dirfd) + finally: + os.close(dirfd) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def service_action(action): + proc = subprocess.run(["systemctl", action, SERVICE], capture_output=True, text=True) + if proc.returncode: + raise CLIError((proc.stderr or proc.stdout).strip() or f"systemctl {action} failed") + + +def rotate_api_password(): + old = api_password() + new = secrets.token_urlsafe(36) + write_env_token(new) + try: + service_action("restart") + last_error = None + for _ in range(12): + try: + request("GET", "/api/users") # Verify the new token is active. + last_error = None + break + except CLIError as exc: + last_error = exc + time.sleep(1) + if last_error: + raise last_error + except CLIError as exc: + write_env_token(old) + try: + service_action("restart") + except CLIError: + pass + raise CLIError(f"Rotation failed; previous password restored: {exc}") from exc + print("New API password:", new) + + +def ask(label, default=""): + suffix = f" [{default}]" if default != "" else "" + result = input(f"{label}{suffix}: ").strip() + return result or str(default) + + +def number(label, default, minimum=0, maximum=1000000): + raw = ask(label, default) + try: + value = int(raw) + except ValueError as exc: + raise CLIError(f"{label} must be a number") from exc + if not minimum <= value <= maximum: + raise CLIError(f"{label} must be between {minimum} and {maximum}") + return value + + +def expiry(default=""): + raw = ask("Expiry (YYYY-MM-DD, days from now, or 'never')", default or "never") + if raw.lower() in ("never", "none", "0"): + return "" + try: + day = dt.date.today() + dt.timedelta(days=int(raw)) if raw.isdecimal() else dt.date.fromisoformat(raw) + return day.isoformat() + "T23:59:59Z" + except ValueError as exc: + raise CLIError("Enter YYYY-MM-DD, number of days, or never") from exc + + +def confirm(label): + return input(label + " Type YES: ").strip() == "YES" + + +def size(n): + n = float(n or 0) + for unit in ("B", "KiB", "MiB", "GiB", "TiB"): + if abs(n) < 1024 or unit == "TiB": + return f"{n:.1f} {unit}" + n /= 1024 + + +def terminal_columns(): + override = os.environ.get("DRAGONCORE_COLUMNS", "") + if override.isdecimal() and 24 <= int(override) <= 240: + return int(override) + return max(24, shutil.get_terminal_size(fallback=(80, 24)).columns) + + +def print_wrapped(value, indent=""): + width = max(20, terminal_columns() - len(indent) - 1) + for part in textwrap.wrap(str(value), width=width, break_long_words=True) or [""]: + print(indent + part) + + +def parse_expiry(value): + if not value: + return None + try: + parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc) + except (TypeError, ValueError): + return None + + +def local_meminfo(): + try: + lines = Path("/proc/meminfo").read_text().splitlines() + values = {k.rstrip(":"): int(v.split()[0]) * 1024 for k, v in (line.split(":", 1) for line in lines)} + total = values["MemTotal"] + return total, max(0, total - values["MemAvailable"]) + except (OSError, KeyError, ValueError): + return 0, 0 + + +def collect_vps_status(): + """Read live host and DragonCore data; degraded API data never blocks the menu.""" + try: + os_name = next((line.split("=", 1)[1].strip().strip('"') + for line in Path("/etc/os-release").read_text().splitlines() + if line.startswith("PRETTY_NAME=")), "Linux") + except OSError: + os_name = "Linux" + try: + seconds = int(float(Path("/proc/uptime").read_text().split()[0])) + uptime = f"{seconds // 86400}d {(seconds % 86400) // 3600}h" + except (OSError, ValueError, IndexError): + uptime = "--" + try: + service = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True, text=True) + state = service.stdout.strip() + if state not in ("active", "inactive", "failed", "activating", "deactivating"): + state = "unknown" + except OSError: + state = "unknown" + stats = users = xray = None + for path, key in (("/api/stats", "stats"), ("/api/users", "users"), + ("/api/xray/status", "xray")): + try: + value = request("GET", path, timeout=2) + except (CLIError, ValueError): + value = None + if key == "stats": + stats = value if isinstance(value, dict) else None + elif key == "users": + users = value if isinstance(value, list) else None + else: + xray = value if isinstance(value, dict) else None + + total_mem, used_mem = local_meminfo() + if stats and stats.get("mem_total_bytes"): + total_mem = stats["mem_total_bytes"] + used_mem = stats.get("mem_used_bytes", 0) + now = dt.datetime.now(dt.timezone.utc) + expired = sum(1 for u in users or [] if (e := parse_expiry(u.get("expires_at"))) and e <= now) + interfaces = (stats or {}).get("interfaces") or [] + try: + disk = shutil.disk_usage("/") + disk_pct = 100 * disk.used / disk.total if disk.total else 0 + except OSError: + disk_pct = 0 + return { + "host": os.uname().nodename, "os": os_name, "uptime": uptime, + "time": dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M"), + "cores": os.cpu_count() or 1, "cpu": (stats or {}).get("cpu_percent"), + "mem_total": total_mem, "mem_used": used_mem, + "disk_pct": disk_pct, + "ssh_total": len(users) if users is not None else None, + "ssh_online": sum(1 for u in users or [] if u.get("active_conns", 0) > 0) if users is not None else None, + "ssh_expired": expired if users is not None else None, + "xray_online": xray.get("online_users") if xray else None, + "down_mbps": max((item.get("rx_mbps", 0) for item in interfaces), default=0), + "up_mbps": max((item.get("tx_mbps", 0) for item in interfaces), default=0), + "service": state, "api_online": stats is not None and users is not None, + } + + +def render_vps_status(s, columns=None): + """Render VPS status within the terminal width, including narrow phones.""" + cols = columns or terminal_columns() + width = min(74, max(20, cols - 4)) + def field(value): + return "--" if value is None else str(value) + def line(value): + return "┃ " + value.ljust(width) + " ┃" + cpu = "--" if s["cpu"] is None else f"{s['cpu']:.1f}%" + ram = (f"{size(s['mem_used'])}/{size(s['mem_total'])}" + if s["mem_total"] else "--") + if cols < 60: + rows = [ + "DRAGONCORESSH • VPS", + f"OS: {s['os']}", + f"Host: {s['host']} {s['time'][-5:]}", + f"CPU: {cpu} / {s['cores']} cores", + f"RAM: {ram} Disk: {s['disk_pct']:.0f}%", + f"Uptime: {s['uptime']} Service: {s['service']}", + f"SSH: {field(s['ssh_online'])} on / {field(s['ssh_total'])} total", + f"Expired: {field(s['ssh_expired'])} Xray: {field(s['xray_online'])} on", + f"Net: ↓ {s['down_mbps']:.1f} ↑ {s['up_mbps']:.1f} Mbps" + if s["api_online"] else "API offline; VPS data local", + ] + else: + rows = [ + "DRAGONCORESSH • VPS STATUS", + f"OS: {s['os']} Host: {s['host']}", + f"Time: {s['time']} Uptime: {s['uptime']} Service: {s['service']}", + f"CPU: {cpu} ({s['cores']} cores) RAM: {ram} Disk: {s['disk_pct']:.0f}%", + f"SSH: {field(s['ssh_online'])} online | {field(s['ssh_expired'])} expired | " + f"{field(s['ssh_total'])} total Xray: {field(s['xray_online'])} online", + f"Network: ↓ {s['down_mbps']:.2f} Mbps ↑ {s['up_mbps']:.2f} Mbps" + if s["api_online"] else "API: unavailable; local VPS metrics shown above", + ] + wrapped = (piece for row in rows for piece in textwrap.wrap(row, width=width, break_long_words=True)) + return "\n".join(["┏" + "━" * (width + 2) + "┓", *(line(part) for part in wrapped), + "┗" + "━" * (width + 2) + "┛"]) + + +def list_users(): + users = request("GET", "/api/users") or [] + if terminal_columns() < 72: + for u in sorted(users, key=lambda row: row["username"]): + print_wrapped(f"{u['username']} {u.get('active_conns', 0)}/{u.get('max_connections', 0)} online") + print_wrapped(f"Usage {size(u.get('total_bytes', 0))} " + f"Expires {str(u.get('expires_at') or 'never')[:10]}", " ") + else: + print(f"{'USER':<24} {'ONLINE':>6} {'LIMIT':>6} {'USAGE':>12} EXPIRES") + for u in sorted(users, key=lambda row: row["username"]): + print(f"{u['username']:<24} {u.get('active_conns', 0):>6} " + f"{u.get('max_connections', 0):>6} {size(u.get('total_bytes', 0)):>12} " + f"{str(u.get('expires_at') or 'never')[:10]}") + print(f"Total: {len(users)}") + return users + + +def user_payload(u): + fields = ("username", "max_connections", "limit_mbps_up", "limit_mbps_down", + "data_quota_bytes", "quota_action", "quota_throttle_mbps", "totp_secret", + "totp_period", "totp_window", "totp_digits", "allow_static_password", + "use_pam", "owner_username") + p = {field: u[field] for field in fields if field in u} + p["expires_at"] = u.get("expires_at") or "" + return p + + +def get_user(name): + return next((u for u in request("GET", "/api/users") or [] if u["username"] == name), None) + + +def create_user(default_days=30, test_hours=None): + name = ask("SSH username").lower() + if not name: + raise CLIError("Username required") + if get_user(name): + raise CLIError("User exists; choose Edit SSH user") + password = secrets.token_urlsafe(18) + expires_at = ((dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=test_hours)).isoformat(timespec="seconds") + if test_hours else expiry(str(default_days))) + p = {"username": name, "password": password, "max_connections": number("Max connections", 1, 0, 10000), + "expires_at": expires_at, "limit_mbps_up": 0, "limit_mbps_down": 0, + "data_quota_bytes": 0, "quota_action": "throttle", "quota_throttle_mbps": 10} + request("POST", "/api/users/create", p) + print(f"SSH user: {name}\nGenerated SSH password: {password}") + + +def edit_user(): + name = ask("SSH username").lower() + u = get_user(name) + if not u: + raise CLIError("User not found") + p = user_payload(u) + print("1 Expiry 2 Connections 3 Bandwidth 4 Quota 5 Generate new password") + choice = ask("Option") + if choice == "1": + p["expires_at"] = expiry(str(u.get("expires_at") or "")[:10]) + elif choice == "2": + p["max_connections"] = number("Max connections", u.get("max_connections", 1), 0, 10000) + elif choice == "3": + p["limit_mbps_up"] = number("Upload Mbps (0 = default)", u.get("limit_mbps_up", 0)) + p["limit_mbps_down"] = number("Download Mbps (0 = default)", u.get("limit_mbps_down", 0)) + elif choice == "4": + gib = number("Quota GiB (0 = unlimited)", round(u.get("data_quota_bytes", 0) / 1024**3)) + p["data_quota_bytes"] = gib * 1024**3 + p["quota_action"] = ask("On quota: throttle/block", u.get("quota_action") or "throttle") + p["quota_throttle_mbps"] = number("Throttle Mbps", u.get("quota_throttle_mbps") or 10) + elif choice == "5": + p["password"] = secrets.token_urlsafe(18) + else: + return + request("POST", "/api/users/create", p) + print("Saved.") + if choice == "5": + print("Generated SSH password:", p["password"]) + + +def delete_user(): + name = ask("SSH username").lower() + if confirm(f"Delete SSH user {name}?"): + request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name})) + print("Deleted.") + + +def reset_traffic(): + name = ask("SSH username").lower() + if confirm(f"Reset usage for {name}?"): + request("POST", "/api/users/reset-traffic", {"username": name}) + print("Traffic reset.") + + +def delete_expired_users(): + now = dt.datetime.now(dt.timezone.utc) + expired = [u["username"] for u in request("GET", "/api/users") or [] + if (end := parse_expiry(u.get("expires_at"))) and end <= now] + if not expired: + print("No expired SSH users.") + return + print("Expired SSH users:", ", ".join(expired)) + if confirm(f"Delete all {len(expired)} expired SSH users?"): + for name in expired: + request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name})) + print(f"Deleted {len(expired)} SSH users.") + + +def user_report(): + for u in request("GET", "/api/users") or []: + print() + print_wrapped(f"{u['username']} | connections {u.get('active_conns', 0)}/{u.get('max_connections', 0)}" + f" | expires {str(u.get('expires_at') or 'never')[:10]}") + quota = u.get("data_quota_bytes", 0) + print_wrapped(f"Usage {size(u.get('total_bytes', 0))}/{size(quota) if quota else 'unlimited'}" + f" | speed ↑ {size(u.get('up_bytes_per_sec', 0))}/s" + f" ↓ {size(u.get('down_bytes_per_sec', 0))}/s", " ") + + +def xray_inbounds(): + inbounds = request("GET", "/api/xray/inbounds") or [] + for inbound in inbounds: + endpoint = ("shared SSH/TLS ports" if inbound.get("shared_port") else + f"port {inbound.get('port')}") + print_wrapped(f"{inbound.get('tag')} ({inbound.get('protocol')}/{inbound.get('network') or 'tcp'}, " + f"{endpoint}, path {inbound.get('path') or '-'})") + for c in inbound.get("clients") or []: + print_wrapped(f"{c.get('name') or c.get('email') or c.get('uuid')} " + f"online={c.get('online', False)} " + f"usage={size(c.get('total_bytes', 0))}", " ") + print_wrapped(str(c.get('uuid')), " ") + return inbounds + + +def xray_shared_port(): + """Configure an HTTP transport on the panel's existing public ports.""" + server = request("GET", "/api/server/config") + xray = server.get("xray") or {} + if xray.get("mode", "native") == "external": + raise CLIError("Shared ports require native Xray emulator mode") + listeners = [server.get("listen") or "0.0.0.0:80", *(server.get("extra_listen") or [])] + tls_listeners = [entry.get("listen") for entry in server.get("tls_forwarders") or []] + print_wrapped("Public SSH/HTTP: " + ", ".join(listeners)) + if tls_listeners: + print_wrapped("Public TLS: " + ", ".join(tls_listeners)) + config = request("GET", "/api/xray/config") + inbounds = config.setdefault("inbounds", []) + candidates = [ib for ib in inbounds if ib.get("protocol") in ("vless", "vmess")] + for ib in candidates: + print_wrapped(f"{ib.get('tag')} ({ib.get('protocol')})" + + (" [shared]" if ib.get("dragoncoreSharedPort") else ""), " ") + tag = ask("Inbound tag (new or listed)") + if not tag or any(ch.isspace() for ch in tag): + raise CLIError("Enter a tag without spaces") + inbound = next((ib for ib in candidates if ib.get("tag") == tag), None) + if inbound is None and any(ib.get("tag") == tag for ib in inbounds): + raise CLIError("That tag belongs to an unsupported inbound") + transport = ask("Transport (ws/xhttp)", + ((inbound or {}).get("streamSettings") or {}).get("network", "ws")).lower() + transport = {"websocket": "ws", "splithttp": "xhttp"}.get(transport, transport) + if transport not in ("ws", "xhttp"): + raise CLIError("Shared port requires ws or xhttp") + existing_paths = set() + for ib in inbounds: + if ib is inbound or not ib.get("dragoncoreSharedPort"): + continue + stream = ib.get("streamSettings") or {} + settings = stream.get("wsSettings") if stream.get("network") in ("ws", "websocket") else stream.get("xhttpSettings") + path = (settings or {}).get("path", "").rstrip("/") + existing_paths.add(path) + def overlaps_shared(path): + return any(path == old or path.startswith(old + "/") or old.startswith(path + "/") + for old in existing_paths) + + auto = next(f"/c{i}" for i in range(1, 10000) if not overlaps_shared(f"/c{i}")) + old_stream = (inbound or {}).get("streamSettings") or {} + old_settings = old_stream.get("wsSettings" if transport == "ws" else "xhttpSettings") or {} + entered = ask("Path (blank generates one)", old_settings.get("path", "")) + path = entered or auto + if not path.startswith("/"): + path = "/" + path + path = path.rstrip("/") + if path in ("", "/") or any(ch in path for ch in "?#%\\ \t\r\n") or "//" in path or any( + segment in (".", "..") for segment in path.split("/")): + raise CLIError("Use a distinct URL path like /c1") + if overlaps_shared(path): + raise CLIError("Path overlaps another shared Xray inbound") + if inbound is None: + protocol = ask("Protocol (vless/vmess)", "vless").lower() + if protocol not in ("vless", "vmess"): + raise CLIError("Protocol must be vless or vmess") + client_uuid = str(uuid.uuid4()) + inbound = {"tag": tag, "protocol": protocol, + "settings": {"clients": [{"id": client_uuid, "email": tag + "@dragoncore.local"}]}} + inbounds.append(inbound) + print("Generated client UUID:", client_uuid) + else: + print_wrapped("The existing inbound transport will change; its clients are preserved.") + # Port is informational for shared inbounds: the panel already owns all + # public sockets. Clients use the port of whichever SSH/TLS listener they choose. + inbound["port"] = int(listeners[0].rsplit(":", 1)[-1]) + inbound["dragoncoreSharedPort"] = True + stream = inbound.setdefault("streamSettings", {}) + stream["network"] = transport + stream["security"] = "none" # the panel's TLS forwarder terminates TLS + stream.pop("tlsSettings", None) + stream.pop("wsSettings", None) + stream.pop("xhttpSettings", None) + stream.pop("splithttpSettings", None) + stream["wsSettings" if transport == "ws" else "xhttpSettings"] = {"path": path} + print_wrapped(f"Shared {transport.upper()} path: {path}") + if not confirm("Save and apply this Xray inbound?"): + return + request("POST", "/api/xray/config", config) + status = request("GET", "/api/xray/status") or {} + action = "restart" if status.get("running") else "start" + request("POST", f"/api/xray/{action}", {}) + print_wrapped("Active on the public SSH/HTTP ports and configured TLS ports." + " Set the client path above; use TLS security in the client when using a TLS port.") + + +def xray_create(): + inbounds = xray_inbounds() + tag = ask("Inbound tag") + if not any(x.get("tag") == tag for x in inbounds): + raise CLIError("Choose an inbound tag from the list") + name = ask("Client name") + if not name: + raise CLIError("Client name required") + client_uuid = str(uuid.uuid4()) + data = {"inbound_tag": tag, "uuid": client_uuid, + "name": name, "email": name.lower().replace(" ", "-") + "@dragoncore.local", + "expires_at": expiry("30"), "max_connections": 0, + "data_quota_bytes": 0, "quota_action": "block", "quota_throttle_mbps": 1} + request("POST", "/api/xray/clients/add", data) + print("Created Xray client UUID:", client_uuid) + + +def xray_delete(): + tag = ask("Inbound tag") + client_uuid = ask("Client UUID") + if confirm(f"Delete Xray client {client_uuid}?"): + query = urllib.parse.urlencode({"inbound_tag": tag, "uuid": client_uuid}) + request("DELETE", "/api/xray/clients/remove?" + query) + print("Deleted.") + + +def xray_edit(): + client_uuid = ask("Client UUID") + client = next((c for inbound in request("GET", "/api/xray/inbounds") or [] + for c in inbound.get("clients") or [] if c.get("uuid") == client_uuid), None) + if not client: + raise CLIError("Xray client not found") + p = {"uuid": client_uuid, "name": client.get("name") or "", + "email": client.get("email") or "", "expires_at": client.get("expires_at") or "", + "max_connections": client.get("max_conns") or 0, + "data_quota_bytes": client.get("data_quota_bytes") or 0, + "quota_action": client.get("quota_action") or "block", + "quota_throttle_mbps": client.get("quota_throttle_mbps") or 1} + print("1 Expiry 2 Connection limit 3 Quota 4 Name") + choice = ask("Option") + if choice == "1": + p["expires_at"] = expiry(str(p["expires_at"])[:10]) + elif choice == "2": + p["max_connections"] = number("Max connections (0 = unlimited)", p["max_connections"], 0, 10000) + elif choice == "3": + p["data_quota_bytes"] = number("Quota GiB (0 = unlimited)", round(p["data_quota_bytes"] / 1024**3)) * 1024**3 + p["quota_action"] = ask("On quota: block/throttle", p["quota_action"]) + p["quota_throttle_mbps"] = number("Throttle Mbps", p["quota_throttle_mbps"]) + elif choice == "4": + p["name"] = ask("Name", p["name"]) + else: + return + request("POST", "/api/xray/clients/update", p) + print("Saved.") + + +def xray_reset_traffic(): + client_uuid = ask("Client UUID") + if confirm(f"Reset traffic for {client_uuid}?"): + request("POST", "/api/xray/clients/reset-traffic", {"uuid": client_uuid}) + print("Traffic reset.") + + +def edit_json(path): + data = request("GET", path) + fd, name = tempfile.mkstemp(prefix="dragoncore-", suffix=".json") + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as out: + json.dump(data, out, indent=2, ensure_ascii=False) + out.write("\n") + before = Path(name).read_bytes() + editor = shlex.split(os.environ.get("EDITOR") or (shutil.which("nano") or shutil.which("vi") or "")) + if not editor or subprocess.run([*editor, name]).returncode: + raise CLIError("No working editor (install nano or set EDITOR); changes discarded") + after = Path(name).read_bytes() + if after == before: + print("No changes.") + return + updated = json.loads(after) + if not confirm("Apply these configuration changes through the API?"): + return + request("POST", path, updated) + print("Configuration saved.") + finally: + os.unlink(name) + + +def set_banner(): + cfg = request("GET", "/api/server/config") + print("Enter banner text, finish with a line containing only a dot:") + lines = [] + while True: + line = input() + if line == ".": + break + lines.append(line) + cfg["banner"] = "\n".join(lines) + request("POST", "/api/server/config", cfg) + print("Banner applied.") + + +def set_ssh_ports(): + cfg = request("GET", "/api/server/config") + cfg["listen"] = ask("Primary SSH address (IP:port)", cfg.get("listen") or "0.0.0.0:80") + current = ", ".join(cfg.get("extra_listen") or []) + extras = input(f"Extra addresses, comma separated [{current}] (enter - to clear): ").strip() + extras = "" if extras == "-" else (extras or current) + cfg["extra_listen"] = [part.strip() for part in extras.split(",") if part.strip()] + result = request("POST", "/api/server/config", cfg) + print("SSH listener settings applied.") + if result: + print(json.dumps(result, indent=2)[:2000]) + + +def set_ssh_limits(): + cfg = request("GET", "/api/server/config") + cfg["default_limit_mbps_up"] = number("Default upload Mbps (0 = unlimited)", cfg.get("default_limit_mbps_up", 0)) + cfg["default_limit_mbps_down"] = number("Default download Mbps (0 = unlimited)", cfg.get("default_limit_mbps_down", 0)) + cfg["max_total_connections"] = number("Global SSH connection cap (0 = default)", cfg.get("max_total_connections", 0), 0, 1000000) + request("POST", "/api/server/config", cfg) + print("Default limits applied.") + + +def status(): + print(render_vps_status(collect_vps_status())) + try: + stats = request("GET", "/api/stats") + print("\nNetwork interfaces:") + for iface in stats.get("interfaces") or []: + if terminal_columns() < 72: + print_wrapped(f"{iface['name']} ↓ {iface.get('rx_mbps', 0):.2f} Mbps " + f"↑ {iface.get('tx_mbps', 0):.2f} Mbps", " ") + print_wrapped(f"RX {size(iface.get('rx_bytes', 0))} " + f"TX {size(iface.get('tx_bytes', 0))}", " ") + else: + print(f" {iface['name']:<18} ↓ {iface.get('rx_mbps', 0):>8.2f} Mbps " + f"↑ {iface.get('tx_mbps', 0):>8.2f} Mbps " + f"RX {size(iface.get('rx_bytes', 0))} TX {size(iface.get('tx_bytes', 0))}") + except CLIError as exc: + print(exc) + + +def connection_status(): + cfg = request("GET", "/api/server/config") + print_wrapped("Public SSH: " + ", ".join([cfg.get("listen", "--"), *(cfg.get("extra_listen") or [])])) + print_wrapped("Local SSH: " + cfg.get("local_ssh_listen", "127.0.0.1:2222")) + for listener in cfg.get("tls_forwarders") or []: + print_wrapped("TLS SSH: " + listener.get("listen", "--")) + for name, label, fields in ( + ("bhttp", "BHTTP", ("listen", "shared_ports")), + ("hcr", "HCR", ("listen", "shared_ports")), + ("btun", "BTUN", ("tcp_listen", "udp_listen", "shared_ports")), + ("dnstt", "DNSTT", ("domain", "udp_listen")), + ("udpgw", "UDPGW", ("listen",)), + ("xray", "Xray", ("mode", "enabled")), + ): + block = cfg.get(name) + if block is None: + print(f"{label}: disabled") + else: + details = " ".join(f"{f}={block[f]}" for f in fields if f in block) + print_wrapped(f"{label}: configured {details}") + + +def protocol_stats(): + for label, path in (("DNSTT", "/api/dnstt"), ("BHTTP", "/api/bhttp"), + ("HCR", "/api/hcr"), ("BTUN", "/api/btun")): + try: + print(f"\n{label}: {json.dumps(request('GET', path), indent=2)[:1200]}") + except CLIError as exc: + print(f"{label}: {exc}") + + +def protocol_logs(): + print("1 DNSTT 2 BHTTP 3 HCR 4 BTUN") + selected = ask("Protocol") + endpoint = {"1": "dnstt", "2": "bhttp", "3": "hcr", "4": "btun"}.get(selected) + if not endpoint: + raise CLIError("Invalid protocol") + result = request("GET", f"/api/{endpoint}/logs") + if isinstance(result, list): + print("\n".join(str(line) for line in result[-60:])) + else: + print(json.dumps(result, indent=2)[-8000:]) + + +def generate_tls_certificate(lets_encrypt=False): + domain = ask("Certificate domain") + if not domain: + raise CLIError("Domain required") + payload = {"domain": domain} + path = "/api/tls/generate-selfsigned" + if lets_encrypt: + payload["email"] = ask("Contact email") + path = "/api/tls/letsencrypt" + result = request("POST", path, payload) + print(json.dumps(result, indent=2)) + + +def regenerate_dnstt_key(): + if confirm("Replace the DNSTT private key? Existing client keys will stop working."): + print(json.dumps(request("POST", "/api/dnstt/genkey", {}), indent=2)) + + +def connection_menu(): + menu("CONNECTION MODES", { + "1": ("Ports and transports", connection_status), + "2": ("DNSTT / BHTTP / HCR / BTUN statistics", protocol_stats), + "3": ("Edit listeners and protocol settings", lambda: edit_json("/api/server/config")), + "4": ("TLS certificates", lambda: print(json.dumps(request("GET", "/api/tls/certs"), indent=2))), + "5": ("DNSTT public key", lambda: print(json.dumps(request("GET", "/api/dnstt/pubkey"), indent=2))), + "6": ("Protocol logs", protocol_logs), + "7": ("Generate self-signed TLS certificate", generate_tls_certificate), + "8": ("Request Let's Encrypt certificate", lambda: generate_tls_certificate(True)), + "9": ("Regenerate DNSTT key", regenerate_dnstt_key), + }) + + +def traffic_history(): + data = request("GET", "/api/vnstat") + print(f"Today: {size(data.get('today_total_bytes', 0))} " + f"This month: {size(data.get('month_total_bytes', 0))}") + for label in ("daily", "monthly"): + print(f"\n{label.title()} by interface:") + for row in data.get(label) or []: + print_wrapped(f"{row.get('period', '--')} {row.get('iface', '--')} " + f"↓ {size(row.get('rx_bytes', 0))} " + f"↑ {size(row.get('tx_bytes', 0))}", " ") + + +def system_log_view(): + source = ask("Log source: panel/dnstt/xray", "panel").lower() + if source not in ("panel", "dnstt", "xray"): + raise CLIError("Choose panel, dnstt or xray") + data = request("GET", f"/api/system/logs?source={source}&lines=100") + print("\n".join(data.get("lines") or [])) + + +def observability_menu(): + menu("VPS AND TRAFFIC", { + "1": ("VPS and live network rates", status), + "2": ("SSH online / traffic report", user_report), + "3": ("Xray online / clients", xray_inbounds), + "4": ("Daily and monthly traffic", traffic_history), + "5": ("System logs", system_log_view), + "6": ("Build and update status", lambda: print(json.dumps(request("GET", "/api/system/update-status"), indent=2))), + }) + + +def logs(): + subprocess.run(["journalctl", "-u", SERVICE, "-n", "80", "--no-pager"]) + + +def render_menu(title, options, vps_status=None, columns=None): + cols = columns or terminal_columns() + width = min(48, max(20, cols - 2)) + lines = [] + if vps_status is not None: + lines.extend((render_vps_status(vps_status, cols), "")) + heading = " DRAGONCORESSH │ " + title + lines.extend(("═" * width, *textwrap.wrap(heading, width=width), "═" * width)) + for key, (label, _) in options.items(): + prefix = f" {key:>2} " + parts = textwrap.wrap(label, width=width - len(prefix), break_long_words=True) or [""] + lines.append(prefix + parts[0]) + lines.extend(" " * len(prefix) + part for part in parts[1:]) + lines.append(" 0 Back / exit") + return "\n".join(lines) + + +def menu(title, options): + while True: + vps = collect_vps_status() if title == "MAIN MENU" else None + print("\n" + render_menu(title, options, vps)) + choice = input("Choose: ").strip().lstrip("0") or "0" + if choice == "0": + return + entry = options.get(choice) + if not entry: + print("Invalid option.") + continue + try: + entry[1]() + except (CLIError, ValueError, json.JSONDecodeError, OSError) as exc: + print("Error:", exc) + except KeyboardInterrupt: + print("\nCancelled.") + + +def ssh_menu(): + menu("SSH ACCOUNTS", {"1": ("List / online / usage", list_users), + "2": ("Create (generated password)", create_user), + "3": ("Create test (24 hours)", lambda: create_user(test_hours=24)), + "4": ("Edit / renew / reset password", edit_user), + "5": ("Detailed account report", user_report), + "6": ("Reset traffic", reset_traffic), + "7": ("Delete expired users", delete_expired_users), + "8": ("Delete one user", delete_user)}) + + +def xray_action(action): + request("POST", f"/api/xray/{action}", {}) + print(f"Xray {action} completed.") + + +def xray_menu(): + menu("XRAY", {"1": ("Inbounds and clients", xray_inbounds), + "2": ("Create client (generated UUID)", xray_create), + "3": ("Edit client", xray_edit), + "4": ("Reset client traffic", xray_reset_traffic), + "5": ("Delete client", xray_delete), + "6": ("Status", lambda: print(json.dumps(request("GET", "/api/xray/status"), indent=2))), + "7": ("Edit Xray JSON", lambda: edit_json("/api/xray/config")), + "8": ("Start Xray", lambda: xray_action("start")), + "9": ("Stop Xray", lambda: xray_action("stop") if confirm("Stop Xray connections?") else None), + "10": ("Restart Xray", lambda: xray_action("restart")), + "11": ("Xray logs", lambda: print(json.dumps(request("GET", "/api/xray/logs"), indent=2)[-8000:])), + "12": ("Repair Xray stats", lambda: request("POST", "/api/xray/stats/repair", {}) if confirm("Repair Xray statistics?") else None), + "13": ("Share SSH/TLS ports (WS/XHTTP)", xray_shared_port)}) + + +def config_menu(): + menu("CONFIGURATION", {"1": ("Set SSH banner", set_banner), + "2": ("Change SSH listener ports", set_ssh_ports), + "3": ("Default bandwidth / connection limits", set_ssh_limits), + "4": ("All SSH / DNSTT / BHTTP / BTUN / HCR settings", lambda: edit_json("/api/server/config")), + "5": ("Xray JSON", lambda: edit_json("/api/xray/config")), + "6": ("Telegram bot configuration", lambda: print(json.dumps(request("GET", "/api/bot/config"), indent=2))), + "7": ("Managed servers", lambda: print(json.dumps(request("GET", "/api/servers"), indent=2)))}) + + +def api_menu(): + menu("API PASSWORD", {"1": ("View current password", lambda: print("API password:", api_password())), + "2": ("Generate new password and restart service", rotate_api_password)}) + + +def main_menu_options(): + return { + "1": ("SSH accounts", ssh_menu), + "2": ("Xray accounts and service", xray_menu), + "3": ("Connection modes and ports", connection_menu), + "4": ("VPS status, users and traffic", observability_menu), + "5": ("Configuration", config_menu), + "6": ("API password (view / rotate)", api_menu), + "7": ("Recent logs", logs), + "8": ("Restart service", lambda: service_action("restart")), + } + + +def main(): + parser = argparse.ArgumentParser(description="DragonCoreSSH CLI administration") + parser.add_argument("--mobile", action="store_true", help="force a 40-column phone layout") + parser.add_argument("command", nargs="?", choices=("menu", "status", "users", "api-password", "logs"), default="menu") + parser.add_argument("action", nargs="?", choices=("show", "change")) + args = parser.parse_args() + require_root() + if args.mobile: + os.environ["DRAGONCORE_COLUMNS"] = "40" + if args.command == "api-password": + if args.action == "show": + print(api_password()) + elif args.action == "change": + rotate_api_password() + else: + api_menu() + elif args.action: + parser.error("action is only valid with api-password") + elif args.command == "users": + list_users() + elif args.command == "status": + status() + elif args.command == "logs": + logs() + else: + menu("MAIN MENU", main_menu_options()) + + +if __name__ == "__main__": + try: + main() + except (CLIError, KeyboardInterrupt) as error: + print(f"Error: {error}", file=sys.stderr) + sys.exit(1) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..bb74798 --- /dev/null +++ b/go.mod @@ -0,0 +1,25 @@ +module shell2 + +go 1.25.4 + +require ( + github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 + github.com/lib/pq v1.10.9 + github.com/openwall/yescrypt-go v1.0.0 + github.com/xtaci/kcp-go/v5 v5.6.61 + github.com/xtaci/smux v1.5.50 + golang.org/x/crypto v0.45.0 + golang.org/x/net v0.47.0 + golang.org/x/time v0.14.0 + www.bamsoftware.com/git/dnstt.git v1.20241021.0 +) + +require ( + github.com/flynn/noise v1.0.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.6 // indirect + github.com/klauspost/reedsolomon v1.12.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/tjfoc/gmsm v1.4.1 // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.31.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2d5ac6b --- /dev/null +++ b/go.sum @@ -0,0 +1,125 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 h1:IEjq88XO4PuBDcvmjQJcQGg+w+UaafSy8G5Kcb5tBhI= +github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5/go.mod h1:exZ0C/1emQJAw5tHOaUDyY1ycttqBAPcxuzf7QbY6ec= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/flynn/noise v1.0.0 h1:DlTHqmzmvcEiKj+4RYo/imoswx/4r6iBlCMfVtrMXpQ= +github.com/flynn/noise v1.0.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= +github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno= +github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/openwall/yescrypt-go v1.0.0 h1:jsGk48zkFvtUjGVOhYPGh+CS595JmTRcKnpggK2AON4= +github.com/openwall/yescrypt-go v1.0.0/go.mod h1:e6CWtFizUEOUttaOjeVMiv1lJaJie3mfOtLJ9CCD6sA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= +github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= +github.com/xtaci/kcp-go/v5 v5.6.61 h1:ajm12pGuWO+GWQNusPyPESC7Rq0yTC2rEXVYkM8ExOg= +github.com/xtaci/kcp-go/v5 v5.6.61/go.mod h1:9O3D8WR+cyyUjGiTILYfg17vn72otWuXK2AFfqIe6CM= +github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM= +github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE= +github.com/xtaci/smux v1.5.50 h1:y/1DlWQC9bnMeZzsyk4oL2hbLK6uVk4BKTz5BeQqUEA= +github.com/xtaci/smux v1.5.50/go.mod h1:IGQ9QYrBphmb/4aTnLEcJby0TNr3NV+OslIOMrX825Q= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= +golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= +golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +www.bamsoftware.com/git/dnstt.git v1.20241021.0 h1:Xi0lmT+5kcgzY7P+r726eBXKMZKgGoD8GTNKrlh8TuE= +www.bamsoftware.com/git/dnstt.git v1.20241021.0/go.mod h1:J4kVFxhn2bZqSqfE9l7keNTtsc+dRR6+uNH4kPu5VIs= diff --git a/hcr_integration.go b/hcr_integration.go new file mode 100644 index 0000000..0fdf5e5 --- /dev/null +++ b/hcr_integration.go @@ -0,0 +1,437 @@ +package main + +// This file embeds the HCR (HTTP/Custom Relay) transport into the panel. HCR is +// a request/response tunnel: the client sends 62-byte-header frames (connect, +// data, poll, ack, close, ping) and the server relays the stream to a target. +// +// Exactly like BHTTP, every HCR session is handed to this process's own SSH +// server through dialInternalSSH, so panel accounts, expiry, TOTP, per-user +// bandwidth limits, data quotas and connection counters all apply. There is no +// dependency on the system sshd, PAM or /etc/shadow. +// +// HCR is built to coexist with BHTTP on the same ports: see tunnel_share.go for +// how a shared listener tells an HCR frame (62-byte header, version byte 0x01) +// apart from a BHTTP frame (29-byte header) and from SSH/HTTP. + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net" + "os" + "strings" + "sync" + "time" + + "shell2/internal/hcr" +) + +// HCRConfig defines the settings for the integrated HCR transport. A nil +// *HCRConfig in the main config disables it entirely. +type HCRConfig struct { + // Listen lists the TCP addresses to bind. IPv6 addresses must use bracket + // form, e.g. "[::]:8181". Empty with SharedPorts off uses the default. + Listen []string `json:"listen"` + + // SharedPorts also accepts HCR on the ports the panel already owns (the + // HTTP+SSH proxy listeners and every TLS forwarder), alongside BHTTP, SSH + // and HTTP-injection clients. See tunnel_share.go. + SharedPorts bool `json:"shared_ports,omitempty"` + + // MaxConnections caps concurrently accepted client sockets. Zero uses a + // safe default; negative disables the cap. + MaxConnections int `json:"max_connections,omitempty"` + + // MaxSessions caps concurrently tracked HCR sessions. Zero uses a safe + // default; negative disables the cap. + MaxSessions int `json:"max_sessions,omitempty"` + + // MaxSourceSessions caps sessions per client IP. Zero disables the per-IP + // cap. + MaxSourceSessions int `json:"max_source_sessions,omitempty"` + + // DownloadPollTimeout bounds a long-poll with no data. Empty defaults to + // "10s". + DownloadPollTimeout string `json:"download_poll_timeout,omitempty"` + + // MaxDownloadFrame is the largest record read from the target per frame, in + // bytes. Zero or out-of-range uses 16384. + MaxDownloadFrame int `json:"max_download_frame,omitempty"` + + // IdleSessionTimeout drops a session that sees no traffic for this long. + // Empty defaults to "5m". + IdleSessionTimeout string `json:"idle_session_timeout,omitempty"` + + // DisableConsoleLog keeps HCR log lines out of stderr. They are still + // captured in memory and served by /api/hcr/logs for the panel. + DisableConsoleLog bool `json:"disable_console_log,omitempty"` + + // LogConnections raises the engine to debug logging (per-frame events). + // Leave off on busy servers. + LogConnections bool `json:"log_connections,omitempty"` + + // AutoRestartInterval controls a watchdog that periodically hard-restarts + // only the HCR listeners and drops their sessions. Empty, "0s", "off" or + // "disabled" turns it off. Minimum accepted value is 1m. + AutoRestartInterval string `json:"auto_restart_interval,omitempty"` + + // AutoRestartGrace is the delay between closing the old listeners and + // binding them again during an auto restart. Empty defaults to "2s". + AutoRestartGrace string `json:"auto_restart_grace,omitempty"` +} + +const ( + defaultHCRListen = "0.0.0.0:8181" + defaultHCRMaxConnections = 10000 + defaultHCRMaxSessions = 10000 + // hcrTargetLabel is only what shows up in logs; HCR never dials a real TCP + // target, it hands each session to the built-in SSH server. + hcrTargetLabel = "hcr" +) + +var ( + hcrMu sync.Mutex + hcrServer *hcr.Server + hcrListeners []net.Listener + hcrAddrs []string + hcrSharedPorts bool + hcrCtx context.Context + hcrCancel context.CancelFunc + + hcrAutoMu sync.Mutex + hcrAutoCancel context.CancelFunc + + hcrLogBuf *ringLogBuffer +) + +func getHCRLogLines() []string { return hcrLogBuf.GetLines() } + +// hcrLogger builds an slog logger that writes into the in-memory ring buffer +// (always) and to stderr (unless the console log is disabled), at debug level +// when connection logging is on. +func hcrLogger(cfg *HCRConfig) *slog.Logger { + level := slog.LevelInfo + if cfg.LogConnections { + level = slog.LevelDebug + } + var writer io.Writer = hcrLogBuf + if !cfg.DisableConsoleLog { + writer = io.MultiWriter(hcrLogBuf, os.Stderr) + } + return slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{Level: level})) +} + +// ---------- Lifecycle ---------- + +func stopHCR() { + stopHCRAutoRestart() + stopHCRInstance() +} + +func stopHCRInstance() { + hcrMu.Lock() + listeners := hcrListeners + server := hcrServer + cancel := hcrCancel + hcrListeners = nil + hcrAddrs = nil + hcrServer = nil + hcrSharedPorts = false + hcrCtx = nil + hcrCancel = nil + hcrMu.Unlock() + + if cancel != nil { + cancel() + } + for _, listener := range listeners { + if listener != nil { + _ = listener.Close() + } + } + if server != nil { + server.Close() + server.Wait() + } +} + +func stopHCRAutoRestart() { + hcrAutoMu.Lock() + defer hcrAutoMu.Unlock() + if hcrAutoCancel != nil { + hcrAutoCancel() + hcrAutoCancel = nil + } +} + +func hcrRunning() bool { + hcrMu.Lock() + defer hcrMu.Unlock() + return hcrServer != nil +} + +// hcrShareEnabled reports whether a running HCR server wants the shared proxy +// and TLS ports. +func hcrShareEnabled() bool { + hcrMu.Lock() + defer hcrMu.Unlock() + return hcrServer != nil && hcrSharedPorts +} + +func hcrListenList() string { + hcrMu.Lock() + addrs := append([]string(nil), hcrAddrs...) + shared := hcrSharedPorts + hcrMu.Unlock() + if shared { + addrs = append(addrs, "shared proxy/TLS ports") + } + return strings.Join(addrs, ", ") +} + +func hcrEnabledInCurrentConfig() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.HCR != nil +} + +// startHCR starts the integrated HCR transport if cfg is non-nil. +func startHCR(cfg *HCRConfig) error { + if cfg == nil { + return nil + } + stopHCRAutoRestart() + if err := startHCRInstance(cfg); err != nil { + return err + } + startHCRAutoRestart(cfg) + return nil +} + +func startHCRInstance(cfg *HCRConfig) error { + if cfg == nil { + return nil + } + if hcrLogBuf == nil { + hcrLogBuf = newRingLogBuffer(200) + } + logger := hcrLogger(cfg) + + addrs := normalizeHCRListenList(cfg.Listen) + if len(addrs) == 0 && !cfg.SharedPorts { + msg := errors.New("hcr: needs either a listen address or shared_ports") + logger.Error(msg.Error()) + return msg + } + cfg.Listen = addrs + + maxConnections := cfg.MaxConnections + if maxConnections == 0 { + maxConnections = defaultHCRMaxConnections + } else if maxConnections < 0 { + maxConnections = 0 + } + maxSessions := cfg.MaxSessions + if maxSessions == 0 { + maxSessions = defaultHCRMaxSessions + } else if maxSessions < 0 { + maxSessions = 0 + } + + server := hcr.NewServer(&hcr.Config{ + TargetAddr: hcrTargetLabel, + DialTarget: func() (net.Conn, error) { return dialInternalSSH(hcrTargetLabel) }, + Logger: logger, + MaxConnections: maxConnections, + MaxSessions: maxSessions, + MaxSourceSessions: cfg.MaxSourceSessions, + DownloadPollTimeout: hcrDurationOrDefault(cfg.DownloadPollTimeout, 10*time.Second, "download_poll_timeout", logger), + MaxDownloadFrame: cfg.MaxDownloadFrame, + IdleSessionTimeout: hcrDurationOrDefault(cfg.IdleSessionTimeout, 5*time.Minute, "idle_session_timeout", logger), + }) + + // Release the previous instance before rebinding the same addresses. + stopHCRInstance() + + listeners := make([]net.Listener, 0, len(addrs)) + bound := make([]string, 0, len(addrs)) + for _, addr := range addrs { + listener, err := net.Listen("tcp", addr) + if err != nil { + for _, opened := range listeners { + _ = opened.Close() + } + server.Close() + msg := fmt.Errorf("hcr: listen failed on %s: %w", addr, err) + logger.Error(msg.Error()) + return msg + } + listeners = append(listeners, listener) + bound = append(bound, addr) + } + + ctx, cancel := context.WithCancel(context.Background()) + hcrMu.Lock() + hcrServer = server + hcrListeners = listeners + hcrAddrs = bound + hcrSharedPorts = cfg.SharedPorts + hcrCtx = ctx + hcrCancel = cancel + hcrMu.Unlock() + + logger.Info("starting", + "listen", bound, "shared_ports", cfg.SharedPorts, + "max_connections", maxConnections, "max_sessions", maxSessions, + "log_connections", cfg.LogConnections) + + for _, listener := range listeners { + go func(current net.Listener) { + defer func() { + if r := recover(); r != nil { + logger.Error("recovered panic in accept loop", "err", r) + } + }() + if err := server.Serve(ctx, current); err != nil && !isListenerClosed(err) { + logger.Warn("listener stopped", "addr", current.Addr().String(), "err", err) + } + }(listener) + } + return nil +} + +func startHCRAutoRestart(cfg *HCRConfig) { + interval := hcrAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := hcrAutoRestartGrace(cfg) + cfgCopy := *cfg + cfgCopy.Listen = append([]string(nil), cfg.Listen...) + ctx, cancel := context.WithCancel(context.Background()) + + hcrAutoMu.Lock() + if hcrAutoCancel != nil { + hcrAutoCancel() + } + hcrAutoCancel = cancel + hcrAutoMu.Unlock() + + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + stopHCRInstance() + if !sleepOrContextDone(ctx, grace) { + return + } + for attempt := 1; ; attempt++ { + if err := startHCRInstance(&cfgCopy); err != nil { + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + continue + } + break + } + } + } + }() +} + +func hcrAutoRestartInterval(cfg *HCRConfig) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.AutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil || d < time.Minute { + return 0 + } + return d +} + +func hcrAutoRestartGrace(cfg *HCRConfig) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace)) + if err != nil || d < 0 { + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +func hcrDurationOrDefault(raw string, fallback time.Duration, field string, logger *slog.Logger) time.Duration { + raw = strings.TrimSpace(raw) + if raw == "" { + return fallback + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + logger.Warn("invalid duration; using default", "field", field, "value", raw, "default", fallback) + return fallback + } + return d +} + +func normalizeHCRListenList(addrs []string) []string { + seen := make(map[string]bool, len(addrs)) + out := make([]string, 0, len(addrs)) + for _, addr := range addrs { + addr = strings.TrimSpace(addr) + if addr == "" || seen[addr] { + continue + } + seen[addr] = true + out = append(out, addr) + } + return out +} + +// hcrConfiguredListen describes the addresses a config asks for, for status +// reports when the server failed to bind them. +func hcrConfiguredListen(cfg *HCRConfig) string { + if cfg == nil { + return "" + } + return strings.Join(normalizeHCRListenList(cfg.Listen), ", ") +} + +// ---------- Stats ---------- + +// HCRStatsSnapshot is what /api/hcr returns. +type HCRStatsSnapshot struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Listen string `json:"listen,omitempty"` + hcr.StatsSnapshot +} + +// GetHCRStatsSnapshot returns the current HCR counters. Safe for concurrent use. +func GetHCRStatsSnapshot() HCRStatsSnapshot { + snapshot := HCRStatsSnapshot{ + Enabled: hcrEnabledInCurrentConfig(), + Running: hcrRunning(), + Listen: hcrListenList(), + } + hcrMu.Lock() + server := hcrServer + hcrMu.Unlock() + if server != nil { + snapshot.StatsSnapshot = server.Stats() + } + return snapshot +} diff --git a/hotreload.go b/hotreload.go new file mode 100644 index 0000000..8cfa72a --- /dev/null +++ b/hotreload.go @@ -0,0 +1,514 @@ +package main + +import ( + "crypto/tls" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "strings" + "sync" + "time" + + "golang.org/x/crypto/ssh" +) + +// ---------- Global SSH config ---------- + +var ( + sshCfgMu sync.RWMutex + currentSSHCfg *ssh.ServerConfig +) + +func setSSHConfig(c *ssh.ServerConfig) { + sshCfgMu.Lock() + currentSSHCfg = c + sshCfgMu.Unlock() +} + +func getSSHConfig() *ssh.ServerConfig { + sshCfgMu.RLock() + defer sshCfgMu.RUnlock() + return currentSSHCfg +} + +// ---------- Dynamic TCP listener pool ---------- + +// listenerPool manages a set of net.Listener instances by address. +// Calling Sync() opens new addresses and closes removed ones; unchanged +// addresses are left untouched so existing connections are not disrupted. +type listenerPool struct { + mu sync.Mutex + entries map[string]net.Listener + serve func(net.Listener) // goroutine launched for each new listener +} + +func newListenerPool(serve func(net.Listener)) *listenerPool { + return &listenerPool{entries: make(map[string]net.Listener), serve: serve} +} + +// Sync ensures exactly addrs are listening. Returns errors for addresses +// that could not be opened. +func (p *listenerPool) Sync(addrs []string) []error { + p.mu.Lock() + defer p.mu.Unlock() + + want := make(map[string]bool, len(addrs)) + for _, a := range addrs { + if a != "" { + want[a] = true + } + } + + for addr, ln := range p.entries { + if !want[addr] { + _ = ln.Close() // causes the serve goroutine to exit + delete(p.entries, addr) + log.Printf("hotreload: stopped %s", addr) + } + } + + var errs []error + for addr := range want { + if _, ok := p.entries[addr]; ok { + continue + } + ln, err := net.Listen("tcp", addr) + if err != nil { + errs = append(errs, fmt.Errorf("listen %s: %w", addr, err)) + continue + } + p.entries[addr] = ln + log.Printf("hotreload: listening on %s", addr) + go p.serve(ln) + } + return errs +} + +func (p *listenerPool) Has(addr string) bool { + if p == nil || addr == "" { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + _, ok := p.entries[addr] + return ok +} + +// StopAll closes every listener in the pool. Active SSH sessions are not owned +// by this pool; callers that want a hard restart should also close tracked SSH +// server connections through userMgr.DisconnectAll(). +func (p *listenerPool) StopAll(reason string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for addr, ln := range p.entries { + _ = ln.Close() + delete(p.entries, addr) + if reason != "" { + log.Printf("hotreload: stopped %s (%s)", addr, reason) + } else { + log.Printf("hotreload: stopped %s", addr) + } + } +} + +func (p *listenerPool) HasAll(addrs []string) bool { + if p == nil { + return false + } + for _, addr := range addrs { + if addr == "" { + continue + } + if !p.Has(addr) { + return false + } + } + return true +} + +// ---------- Dynamic TLS listener pool ---------- + +type tlsListenerPool struct { + mu sync.Mutex + entries map[string]net.Listener +} + +func newTLSListenerPool() *tlsListenerPool { + return &tlsListenerPool{entries: make(map[string]net.Listener)} +} + +// Sync ensures exactly forwarders are listening (matched by listen address). +func (p *tlsListenerPool) Sync(forwarders []TLSForwarderConfig) []error { + p.mu.Lock() + defer p.mu.Unlock() + + want := make(map[string]TLSForwarderConfig, len(forwarders)) + for _, f := range forwarders { + if f.Listen != "" { + want[f.Listen] = f + } + } + + for addr, ln := range p.entries { + if _, ok := want[addr]; !ok { + _ = ln.Close() + delete(p.entries, addr) + log.Printf("hotreload: stopped TLS %s", addr) + } + } + + var errs []error + for addr, fwd := range want { + if _, ok := p.entries[addr]; ok { + continue + } + cert, err := tls.LoadX509KeyPair(fwd.CertFile, fwd.KeyFile) + if err != nil { + errs = append(errs, fmt.Errorf("TLS cert/key %s: %w", addr, err)) + continue + } + ln, err := tls.Listen("tcp", addr, &tls.Config{ + Certificates: []tls.Certificate{cert}, + MinVersion: tls.VersionTLS12, + NextProtos: []string{"h2", "http/1.1"}, + }) + if err != nil { + errs = append(errs, fmt.Errorf("TLS listen %s: %w", addr, err)) + continue + } + p.entries[addr] = ln + log.Printf("hotreload: TLS+SSH listening on %s", addr) + go serveTLSSSH(ln) + } + return errs +} + +func (p *tlsListenerPool) Has(addr string) bool { + if p == nil || addr == "" { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + _, ok := p.entries[addr] + return ok +} + +// Drop closes the listeners for the given addresses so a following Sync rebinds +// them. Used after a certificate is replaced on disk: tls.Listen captures the +// certificate when the listener is created, so the socket has to be recreated +// for new material to be served. Accepted connections are not owned by the pool +// and keep running. +func (p *tlsListenerPool) Drop(addrs []string, reason string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for _, addr := range addrs { + entry, ok := p.entries[addr] + if !ok { + continue + } + _ = entry.Close() + delete(p.entries, addr) + if reason != "" { + log.Printf("hotreload: dropped TLS %s (%s)", addr, reason) + } else { + log.Printf("hotreload: dropped TLS %s", addr) + } + } +} + +func (p *tlsListenerPool) StopAll(reason string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + for addr, ln := range p.entries { + _ = ln.Close() + delete(p.entries, addr) + if reason != "" { + log.Printf("hotreload: stopped TLS %s (%s)", addr, reason) + } else { + log.Printf("hotreload: stopped TLS %s", addr) + } + } +} + +func (p *tlsListenerPool) HasAll(forwarders []TLSForwarderConfig) bool { + if p == nil { + return false + } + for _, f := range forwarders { + if f.Listen == "" { + continue + } + if !p.Has(f.Listen) { + return false + } + } + return true +} + +// ---------- Global pool instances (initialised in main) ---------- + +var ( + publicPool *listenerPool // HTTP+SSH: listen + extra_listen + localPool *listenerPool // raw SSH: loopback-only local_ssh_listen + tlsPool *tlsListenerPool // TLS forwarders +) + +// isListenerClosed reports whether err came from using a closed listener. +func isListenerClosed(err error) bool { + return errors.Is(err, net.ErrClosed) +} + +// ---------- Runtime settings ---------- + +var ( + defaultLimitsMu sync.RWMutex + runtimeLimitMbpsUp int + runtimeLimitMbpsDown int +) + +func setDefaultLimits(up, down int) { + defaultLimitsMu.Lock() + runtimeLimitMbpsUp = up + runtimeLimitMbpsDown = down + defaultLimitsMu.Unlock() +} + +func getDefaultLimits() (up, down int) { + defaultLimitsMu.RLock() + defer defaultLimitsMu.RUnlock() + return runtimeLimitMbpsUp, runtimeLimitMbpsDown +} + +// ---------- Full live reload ---------- + +// applyFullConfigReload applies every field in newCfg to the running server +// without a process restart. Port changes, DNSTT/UDPGW changes, Xray changes, +// and bandwidth defaults all take effect immediately. +// It returns a status report for the API and CLI. +type ServiceReloadStatus struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Listen string `json:"listen,omitempty"` + Error string `json:"error,omitempty"` +} + +type ConfigReloadReport struct { + Applied bool `json:"applied"` + Warnings []string `json:"warnings,omitempty"` + Services map[string]ServiceReloadStatus `json:"services"` +} + +func newReloadReport() ConfigReloadReport { + return ConfigReloadReport{Applied: true, Services: map[string]ServiceReloadStatus{}} +} + +func (r *ConfigReloadReport) warnf(format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + r.Warnings = append(r.Warnings, msg) + log.Printf("config reload: %s", msg) +} + +func joinAddrs(addrs []string) string { + clean := make([]string, 0, len(addrs)) + for _, a := range addrs { + if a = strings.TrimSpace(a); a != "" { + clean = append(clean, a) + } + } + return strings.Join(clean, ", ") +} + +func applyFullConfigReload(newCfg *Config) ConfigReloadReport { + report := newReloadReport() + stopProxyAutoRestart() + // Banner + bt := newCfg.Banner + if bt == "" && newCfg.BannerFile != "" { + if data, err := os.ReadFile(newCfg.BannerFile); err == nil { + bt = string(data) + } + } + setBannerText(bt) + + // Default per-connection bandwidth limits and SSH inactivity cleanup + // (picked up by new connections). + setDefaultLimits(newCfg.DefaultLimitMbpsUp, newCfg.DefaultLimitMbpsDown) + setSSHIdleTimeoutFromConfig(newCfg.SSHIdleTimeout) + setMaxTotalConnsFromConfig(newCfg.MaxTotalConnections) + setPAMAuthEnabled(newCfg.PAMAuthEnabled) + + // Quiet logging / user count display + if newCfg.Quiet { + log.SetOutput(io.Discard) + } else if !newCfg.UserCount { + log.SetOutput(os.Stderr) + } + userCountEnabled = newCfg.UserCount + + // Internal raw SSH listener. Keep it separate from the public listener + // pool so proxy auto-restarts never take the local integration endpoint + // offline. normalizeRuntimePorts guarantees one loopback address here. + localAddrs := []string{newCfg.LocalSSHListen} + for _, e := range localPool.Sync(localAddrs) { + report.warnf("internal SSH listener error: %v", e) + } + report.Services["local_ssh"] = ServiceReloadStatus{ + Enabled: true, + Running: localPool.HasAll(localAddrs), + Listen: newCfg.LocalSSHListen, + } + if !report.Services["local_ssh"].Running { + report.Services["local_ssh"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.LocalSSHListen, Error: "internal SSH listener could not be opened"} + } + + // Public SSH listeners (main listen + extra_listen) + publicAddrs := append([]string{newCfg.Listen}, newCfg.ExtraListen...) + for _, e := range publicPool.Sync(publicAddrs) { + report.warnf("SSH listener error: %v", e) + } + report.Services["ssh"] = ServiceReloadStatus{ + Enabled: true, + Running: publicPool.HasAll(publicAddrs), + Listen: joinAddrs(publicAddrs), + } + if !report.Services["ssh"].Running { + report.Services["ssh"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: joinAddrs(publicAddrs), Error: "one or more SSH listeners could not be opened"} + } + + // TLS forwarders + for _, e := range tlsPool.Sync(newCfg.TLSForwarders) { + report.warnf("TLS listener error: %v", e) + } + if len(newCfg.TLSForwarders) > 0 { + report.Services["tls"] = ServiceReloadStatus{ + Enabled: true, + Running: tlsPool.HasAll(newCfg.TLSForwarders), + Listen: tlsForwarderList(newCfg.TLSForwarders), + } + if !report.Services["tls"].Running { + report.Services["tls"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: tlsForwarderList(newCfg.TLSForwarders), Error: "one or more TLS forwarders could not be opened"} + } + } else { + report.Services["tls"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // DNSTT — stop current instance (no-op if not running) then start new one. + stopDNSTT() + if newCfg.DNSTT != nil { + if err := startDNSTT(newCfg.DNSTT, getSSHConfig()); err != nil { + report.warnf("DNSTT failed to start: %v", err) + report.Services["dnstt"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.DNSTT.UDPListen, Error: err.Error()} + } else { + report.Services["dnstt"] = ServiceReloadStatus{Enabled: true, Running: true, Listen: newCfg.DNSTT.UDPListen} + } + } else { + report.Services["dnstt"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // UDPGW — same pattern. + stopUDPGW() + if newCfg.UDPGW != nil { + if err := startUDPGW(newCfg.UDPGW); err != nil { + report.warnf("UDPGW failed to start: %v", err) + report.Services["udpgw"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.UDPGW.Listen, Error: err.Error()} + } else { + report.Services["udpgw"] = ServiceReloadStatus{Enabled: true, Running: udpgwRunning(), Listen: newCfg.UDPGW.Listen} + } + } else { + report.Services["udpgw"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // BHTTP — stop current instance (no-op if not running) then start new one. + stopBHTTP() + if newCfg.BHTTP != nil { + if err := startBHTTP(newCfg.BHTTP); err != nil { + report.warnf("BHTTP failed to start: %v", err) + report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: joinAddrs(newCfg.BHTTP.Listen), Error: err.Error()} + } else { + report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: bhttpRunning(), Listen: bhttpListenList()} + } + } else { + report.Services["bhttp"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // BTUN — same pattern. A failure here is usually a missing /dev/net/tun or + // an interface name already taken, both of which the panel surfaces. + stopBTUN() + if newCfg.BTUN != nil { + if err := startBTUN(newCfg.BTUN); err != nil { + report.warnf("BTUN failed to start: %v", err) + report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: btunConfiguredListen(newCfg.BTUN), Error: err.Error()} + } else { + report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: btunRunning(), Listen: btunListenList()} + } + } else { + report.Services["btun"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // HCR — stop current instance (no-op if not running) then start new one. + stopHCR() + if newCfg.HCR != nil { + if err := startHCR(newCfg.HCR); err != nil { + report.warnf("HCR failed to start: %v", err) + report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: hcrConfiguredListen(newCfg.HCR), Error: err.Error()} + } else { + report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: hcrRunning(), Listen: hcrListenList()} + } + } else { + report.Services["hcr"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + // Xray — update stored config then restart/stop as needed. + if newCfg.Xray != nil { + newCfg.Xray.NormalizeDefaults() + xrayMgr.mu.Lock() + xrayMgr.cfg = newCfg.Xray + xrayMgr.mu.Unlock() + if !newCfg.Xray.UseNative() { + xrayMgr.startStatsPoller() + } + if newCfg.Xray.Enabled { + if err := xrayMgr.Restart(); err != nil { + report.warnf("Xray failed to restart: %v", err) + } + time.Sleep(500 * time.Millisecond) + st := xrayMgr.Status() + report.Services["xray"] = ServiceReloadStatus{Enabled: true, Running: st.Running, Error: st.Error} + if !st.Running && st.Error == "" { + report.Services["xray"] = ServiceReloadStatus{Enabled: true, Running: false, Error: "xray exited immediately; check logs"} + } + } else { + _ = xrayMgr.Stop() + report.Services["xray"] = ServiceReloadStatus{Enabled: false, Running: false} + } + } else { + _ = xrayMgr.Stop() + report.Services["xray"] = ServiceReloadStatus{Enabled: false, Running: false} + } + + setGlobalCfg(newCfg) + startProxyAutoRestart(newCfg) + return report +} + +func tlsForwarderList(forwarders []TLSForwarderConfig) string { + addrs := make([]string, 0, len(forwarders)) + for _, f := range forwarders { + if strings.TrimSpace(f.Listen) != "" { + addrs = append(addrs, strings.TrimSpace(f.Listen)) + } + } + return strings.Join(addrs, ", ") +} diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..15cd502 --- /dev/null +++ b/install.sh @@ -0,0 +1,716 @@ +#!/bin/bash +# DragonCoreSSH CLI + SSH/Xray service (multi-distro Linux/systemd) +# Usage: sudo bash install.sh +set -euo pipefail + +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m' +info() { echo -e "${GREEN}[+]${NC} $*"; } +warn() { echo -e "${YELLOW}[!]${NC} $*"; } +error() { echo -e "${RED}[x]${NC} $*"; exit 1; } + +# ── config ────────────────────────────────────────────────────────────────── +INSTALL_DIR="/opt/sshpanel" +SERVICE_NAME="sshpanel" +LOG_TMPFS_SIZE="${LOG_TMPFS_SIZE:-15m}" +PANEL_LOG_MAX_BYTES="${PANEL_LOG_MAX_BYTES:-1048576}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +GO_VERSION="${GO_VERSION:-$(awk '$1 == "go" {print $2; exit}' "$SCRIPT_DIR/go.mod" 2>/dev/null || echo "1.22.5")}" +REPO_URL="DragonCoreSSH-CLI local release" +MKDIR_BIN="$(command -v mkdir 2>/dev/null || true)" +[[ -n "$MKDIR_BIN" ]] || MKDIR_BIN="/bin/mkdir" +# ──────────────────────────────────────────────────────────────────────────── + +[[ $EUID -ne 0 ]] && error "Run as root: sudo bash $0" + +# Cross-distro helpers ------------------------------------------------------- +PKG_MANAGER="" +PKG_DEPS=() +PKG_OPTIONAL_DEPS=() +SYSTEMCTL_BIN="" +SH_BIN="$(command -v sh 2>/dev/null || echo /bin/sh)" +MOUNT_BIN="$(command -v mount 2>/dev/null || echo /bin/mount)" +MOUNTPOINT_BIN="$(command -v mountpoint 2>/dev/null || echo /usr/bin/mountpoint)" +TOUCH_BIN="$(command -v touch 2>/dev/null || echo /usr/bin/touch)" +CHMOD_BIN="$(command -v chmod 2>/dev/null || echo /usr/bin/chmod)" + +require_systemd() { + SYSTEMCTL_BIN="$(command -v systemctl 2>/dev/null || true)" + if [[ -z "$SYSTEMCTL_BIN" ]]; then + error "systemd was not found. This installer supports Linux distributions that use systemd for services." + fi +} + +detect_pkg_manager() { + if command -v apt-get >/dev/null 2>&1; then + PKG_MANAGER="apt" + elif command -v dnf >/dev/null 2>&1; then + PKG_MANAGER="dnf" + elif command -v yum >/dev/null 2>&1; then + PKG_MANAGER="yum" + elif command -v zypper >/dev/null 2>&1; then + PKG_MANAGER="zypper" + elif command -v pacman >/dev/null 2>&1; then + PKG_MANAGER="pacman" + elif command -v apk >/dev/null 2>&1; then + PKG_MANAGER="apk" + else + error "No supported package manager found. Supported: apt, dnf, yum, zypper, pacman, apk." + fi +} + +set_package_deps() { + case "$PKG_MANAGER" in + apt) + PKG_DEPS=(curl wget git rsync build-essential postgresql ca-certificates unzip openssh-client openssl python3 tar gzip) + PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables) + ;; + dnf|yum) + PKG_DEPS=(curl wget git rsync gcc make postgresql-server ca-certificates unzip openssh-clients openssl python3 tar gzip) + PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables) + ;; + zypper) + PKG_DEPS=(curl wget git rsync gcc make postgresql-server ca-certificates unzip openssh openssl python3 tar gzip) + PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables) + ;; + pacman) + PKG_DEPS=(curl wget git rsync base-devel postgresql ca-certificates unzip openssh openssl python tar gzip) + PKG_OPTIONAL_DEPS=(iptables-nft nftables) + ;; + apk) + PKG_DEPS=(curl wget git rsync build-base postgresql ca-certificates unzip openssh-client openssl python3 tar gzip) + PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables) + ;; + esac +} + +pkg_update() { + case "$PKG_MANAGER" in + apt) apt-get update -qq ;; + dnf) dnf makecache -q ;; + yum) yum makecache -q ;; + zypper) zypper --non-interactive refresh ;; + pacman) pacman -Sy --noconfirm ;; + apk) apk update ;; + esac +} + +pkg_install() { + case "$PKG_MANAGER" in + apt) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@" ;; + dnf) dnf install -y "$@" ;; + yum) yum install -y "$@" ;; + zypper) zypper --non-interactive install -y "$@" ;; + pacman) pacman -S --noconfirm --needed "$@" ;; + apk) apk add --no-cache "$@" ;; + esac +} + +pkg_install_optional() { + local pkg + for pkg in "$@"; do + pkg_install "$pkg" >/dev/null 2>&1 || warn " Optional package '$pkg' could not be installed; continuing." + done +} + +postgres_data_dir() { + for dir in /var/lib/postgresql/data /var/lib/pgsql/data /var/lib/postgres/data; do + [[ -d "$dir" || -d "$(dirname "$dir")" ]] && { printf '%s\n' "$dir"; return 0; } + done + printf '%s\n' /var/lib/postgresql/data +} + +init_postgresql_if_needed() { + case "$PKG_MANAGER" in + dnf|yum|zypper) + postgresql-setup --initdb >/dev/null 2>&1 || true + ;; + pacman) + local data_dir + data_dir="$(postgres_data_dir)" + if [[ ! -s "$data_dir/PG_VERSION" ]]; then + mkdir -p "$data_dir" + chown -R postgres:postgres "$(dirname "$data_dir")" + if command -v runuser >/dev/null 2>&1; then + runuser -u postgres -- initdb -D "$data_dir" >/dev/null 2>&1 || true + else + su - postgres -c "initdb -D '$data_dir'" >/dev/null 2>&1 || true + fi + fi + ;; + apk) + if command -v rc-service >/dev/null 2>&1; then + rc-service postgresql setup >/dev/null 2>&1 || true + fi + ;; + esac +} + +start_enable_postgresql() { + local started=false svc + for svc in postgresql postgresql.service; do + if "$SYSTEMCTL_BIN" start "$svc" >/dev/null 2>&1; then + "$SYSTEMCTL_BIN" enable "$svc" >/dev/null 2>&1 || true + started=true + break + fi + done + if ! $started && command -v service >/dev/null 2>&1; then + service postgresql start >/dev/null 2>&1 && started=true || true + fi + $started || warn " Could not start PostgreSQL automatically; continuing in case it is already running." +} + +ensure_log_tmpfs_mount() { + local log_dir="${INSTALL_DIR}/logs" + local opts="rw,nosuid,nodev,noexec,noatime,nofail,size=${LOG_TMPFS_SIZE},mode=0755" + local tmp_fstab + + mkdir -p "$log_dir" + + if [[ -f /etc/fstab ]]; then + cp /etc/fstab "/etc/fstab.sshpanel.bak.$(date +%s)" 2>/dev/null || true + tmp_fstab="$(mktemp)" + awk -v mp="$log_dir" '!(($1 == "tmpfs") && ($2 == mp) && ($3 == "tmpfs")) {print}' /etc/fstab > "$tmp_fstab" + printf 'tmpfs %s tmpfs %s 0 0\n' "$log_dir" "$opts" >> "$tmp_fstab" + cat "$tmp_fstab" > /etc/fstab + rm -f "$tmp_fstab" + info " Log RAM disk automount saved in /etc/fstab: $log_dir (${LOG_TMPFS_SIZE})" + else + warn " /etc/fstab not found; service startup fallback will mount $log_dir as tmpfs" + fi + + "${SYSTEMCTL_BIN:-systemctl}" daemon-reload >/dev/null 2>&1 || true + if command -v mountpoint >/dev/null 2>&1 && mountpoint -q "$log_dir"; then + mount -o "remount,size=${LOG_TMPFS_SIZE},mode=0755" "$log_dir" >/dev/null 2>&1 || true + else + mount "$log_dir" >/dev/null 2>&1 || mount -t tmpfs -o "size=${LOG_TMPFS_SIZE},mode=0755" tmpfs "$log_dir" >/dev/null 2>&1 || \ + warn " Could not mount $log_dir as tmpfs now; service startup fallback will try again" + fi + + touch "$log_dir/panel.log" >/dev/null 2>&1 || true + chmod 0644 "$log_dir/panel.log" >/dev/null 2>&1 || true +} + +echo -e "\n${GREEN}══════════════════════════════════════════${NC}" +echo -e "${GREEN} SSH Panel + Xray-core · Installer ${NC}" +echo -e "${GREEN}══════════════════════════════════════════${NC}\n" + +# ── 1. OS / package-manager detection ──────────────────────────────────────── +info "[1/10] Detecting Linux distribution and package manager…" +if [[ -f /etc/os-release ]]; then + # shellcheck disable=SC1091 + . /etc/os-release + OS_ID="${ID:-unknown}" + OS_LIKE="${ID_LIKE:-}" + OS_PRETTY="${PRETTY_NAME:-$OS_ID}" +else + OS_ID="unknown" + OS_LIKE="" + OS_PRETTY="unknown Linux" +fi + +require_systemd +detect_pkg_manager +set_package_deps +info " OS : $OS_PRETTY" +info " ID / ID_LIKE : $OS_ID / ${OS_LIKE:-none}" +info " Package manager: $PKG_MANAGER" +info " Service manager: systemd" + +# ── 2. System dependencies ─────────────────────────────────────────────────── +info "[2/10] Installing system packages…" +pkg_update +pkg_install "${PKG_DEPS[@]}" +pkg_install_optional "${PKG_OPTIONAL_DEPS[@]}" + +# ── 3. Go ──────────────────────────────────────────────────────────────────── +info "[3/10] Installing Go ${GO_VERSION}…" +NEED_GO=true +if command -v go &>/dev/null; then + CURRENT_GO=$(go version 2>/dev/null | awk '{print $3}' | sed 's/go//') + if [[ "$(printf '%s\n' "$GO_VERSION" "$CURRENT_GO" | sort -V | head -1)" == "$GO_VERSION" ]]; then + info " Go $CURRENT_GO already installed — skipping" + NEED_GO=false + fi +fi + +if $NEED_GO; then + MACHINE=$(uname -m) + case "$MACHINE" in + x86_64) GOARCH="amd64" ;; + aarch64) GOARCH="arm64" ;; + armv7l) GOARCH="armv6l" ;; + *) GOARCH="amd64" ;; + esac + GO_URL="https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz" + info " Downloading $GO_URL" + wget -q --show-progress -O /tmp/go.tar.gz "$GO_URL" + rm -rf /usr/local/go + tar -C /usr/local -xzf /tmp/go.tar.gz + rm -f /tmp/go.tar.gz + echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh + chmod +x /etc/profile.d/go.sh +fi + +export PATH=$PATH:/usr/local/go/bin +go version + +# ── 4. Directory layout ────────────────────────────────────────────────────── +info "[4/10] Setting up ${INSTALL_DIR}…" +mkdir -p "$INSTALL_DIR/keys" "$INSTALL_DIR/logs" +ensure_log_tmpfs_mount + +# ── 5. Build SSH panel binary ──────────────────────────────────────────────── +info "[5/10] Building SSH Panel binary…" +cd "$SCRIPT_DIR" +export GOPATH=/tmp/gopath_sshpanel +export GOCACHE=/tmp/gocache_sshpanel +BUILD_COMMIT="$(git -C "$SCRIPT_DIR" rev-parse HEAD 2>/dev/null || true)" +BUILD_BRANCH="$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)" +BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +BUILD_REPO_URL="$(git -C "$SCRIPT_DIR" config --get remote.origin.url 2>/dev/null || true)" +[[ -n "$BUILD_COMMIT" ]] || BUILD_COMMIT="unknown" +[[ -n "$BUILD_BRANCH" && "$BUILD_BRANCH" != "HEAD" ]] || BUILD_BRANCH="main" +[[ -n "$BUILD_REPO_URL" ]] || BUILD_REPO_URL="$REPO_URL" + +go mod download +go mod tidy +go build -ldflags="-s -w -X main.buildCommit=$BUILD_COMMIT -X main.buildBranch=$BUILD_BRANCH -X main.buildTime=$BUILD_TIME" -o "$INSTALL_DIR/sshpanel" . +printf '%s\n' "$BUILD_COMMIT" > "$INSTALL_DIR/.installed_commit" +printf '%s\n' "$BUILD_BRANCH" > "$INSTALL_DIR/.installed_branch" +printf '%s\n' "$BUILD_TIME" > "$INSTALL_DIR/.installed_build_time" +printf '%s\n' "$BUILD_REPO_URL" > "$INSTALL_DIR/.installed_repo_url" +chmod 0644 "$INSTALL_DIR/.installed_commit" "$INSTALL_DIR/.installed_branch" "$INSTALL_DIR/.installed_build_time" +chmod 0600 "$INSTALL_DIR/.installed_repo_url" +info " Binary: $INSTALL_DIR/sshpanel" +info " Build commit: $BUILD_COMMIT ($BUILD_BRANCH)" +install -m 700 "$SCRIPT_DIR/dragoncore_cli.py" "$INSTALL_DIR/dragoncore_cli.py" +ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/dragoncore +if [[ ( -e /usr/local/bin/menu || -L /usr/local/bin/menu ) && "$(readlink -f /usr/local/bin/menu 2>/dev/null || true)" != "$INSTALL_DIR/dragoncore_cli.py" ]]; then + MENU_BACKUP="/usr/local/bin/menu.backup.$(date +%s%N)" + mv /usr/local/bin/menu "$MENU_BACKUP" + warn " Previous menu command saved to $MENU_BACKUP" +fi +ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/menu +info " DragonCoreSSH CLI installed: menu (also dragoncore)" +mkdir -p "$INSTALL_DIR/source" +rsync -a --delete --exclude '.git' --exclude 'source/' --exclude '__pycache__/' "$SCRIPT_DIR/" "$INSTALL_DIR/source/" +if [[ -f "$SCRIPT_DIR/update.sh" ]]; then + cp "$SCRIPT_DIR/update.sh" "$INSTALL_DIR/update.sh" + chmod 700 "$INSTALL_DIR/update.sh" + info " Local CLI updater copied" +fi + +# ── 6. Xray binary ────────────────────────────────────────────────────────── +info "[6/10] Downloading Xray-core…" +XRAY_VER=$(curl -sf "https://api.github.com/repos/XTLS/Xray-core/releases/latest" \ + | grep '"tag_name"' | head -1 | cut -d'"' -f4 || echo "v24.11.30") +MACHINE=$(uname -m) +case "$MACHINE" in + x86_64) XRAY_ARCH="64" ;; + aarch64) XRAY_ARCH="arm64-v8a" ;; + armv7l) XRAY_ARCH="arm32-v7a" ;; + *) XRAY_ARCH="64" ;; +esac +XRAY_URL="https://github.com/XTLS/Xray-core/releases/download/${XRAY_VER}/Xray-linux-${XRAY_ARCH}.zip" +info " Xray ${XRAY_VER} (${XRAY_ARCH})" +wget -q --show-progress -O /tmp/xray.zip "$XRAY_URL" +unzip -o /tmp/xray.zip xray -d "$INSTALL_DIR" > /dev/null 2>&1 || { + mkdir -p /tmp/xray_extract + unzip -o /tmp/xray.zip -d /tmp/xray_extract > /dev/null 2>&1 + mv /tmp/xray_extract/xray "$INSTALL_DIR/xray" +} +chmod +x "$INSTALL_DIR/xray" +rm -f /tmp/xray.zip +"$INSTALL_DIR/xray" version + +# ── 7. PostgreSQL ──────────────────────────────────────────────────────────── +info "[7/10] Configuring PostgreSQL…" +init_postgresql_if_needed +start_enable_postgresql + +DB_NAME="sshpanel" +DB_USER="sshpanel" +DB_PASS=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32 || true) +if [[ ${#DB_PASS} -lt 32 ]]; then + DB_PASS=$(openssl rand -hex 16 2>/dev/null || date +%s%N) +fi + +su -c "psql -tc \"SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}'\" | grep -q 1 || \ + psql -c \"CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASS}';\"" postgres +# Reinstall-safe: if the role already existed, make the new .env password valid. +su -c "psql -c \"ALTER USER ${DB_USER} WITH PASSWORD '${DB_PASS}';\"" postgres + +su -c "psql -tc \"SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'\" | grep -q 1 || \ + psql -c \"CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};\"" postgres +# Reinstall-safe: if the database already existed, make sshpanel its owner. +su -c "psql -c \"ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};\"" postgres + +su -c "psql -d ${DB_NAME} -c \" +CREATE TABLE IF NOT EXISTS ssh_users ( + username TEXT PRIMARY KEY, + password TEXT NOT NULL DEFAULT '', + max_connections INT NOT NULL DEFAULT 0, + expires_at TEXT, + limit_mbps_up INT NOT NULL DEFAULT 0, + limit_mbps_down INT NOT NULL DEFAULT 0, + totp_secret TEXT NOT NULL DEFAULT '', + totp_period INT NOT NULL DEFAULT 60, + totp_window INT NOT NULL DEFAULT 1, + totp_digits INT NOT NULL DEFAULT 6, + allow_static_password BOOLEAN NOT NULL DEFAULT FALSE, + owner_username TEXT NOT NULL DEFAULT '' +); +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_period INT NOT NULL DEFAULT 60; +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_window INT NOT NULL DEFAULT 1; +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_digits INT NOT NULL DEFAULT 6; +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS allow_static_password BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT ''; +ALTER TABLE ssh_users ALTER COLUMN password SET DEFAULT ''; + +CREATE TABLE IF NOT EXISTS ssh_iface_totals ( + iface TEXT PRIMARY KEY, + total_rx_bytes BIGINT NOT NULL DEFAULT 0, + total_tx_bytes BIGINT NOT NULL DEFAULT 0, + last_kernel_rx_bytes BIGINT NOT NULL DEFAULT 0, + last_kernel_tx_bytes BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS total_rx_bytes BIGINT NOT NULL DEFAULT 0; +ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS total_tx_bytes BIGINT NOT NULL DEFAULT 0; +ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS last_kernel_rx_bytes BIGINT NOT NULL DEFAULT 0; +ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS last_kernel_tx_bytes BIGINT NOT NULL DEFAULT 0; +ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); + +CREATE TABLE IF NOT EXISTS admin_users ( + id SERIAL PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'reseller', + max_users INT NOT NULL DEFAULT 30, + expires_at TIMESTAMPTZ, + is_active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS xray_clients ( + uuid TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + inbound_tag TEXT NOT NULL DEFAULT '', + expires_at TIMESTAMPTZ, + max_conns INT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- Telegram sales bot (created idempotently by the app too; mirrored here for a clean install) +CREATE TABLE IF NOT EXISTS bot_users ( + telegram_id BIGINT PRIMARY KEY, + username TEXT NOT NULL DEFAULT '', + first_name TEXT NOT NULL DEFAULT '', + role TEXT NOT NULL DEFAULT 'customer', + linked_admin_username TEXT NOT NULL DEFAULT '', + credit_balance INT NOT NULL DEFAULT 0, + trial_used BOOLEAN NOT NULL DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS bot_plans ( + id SERIAL PRIMARY KEY, name TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT 'ssh', + days INT NOT NULL DEFAULT 30, max_connections INT NOT NULL DEFAULT 1, + limit_mbps_up INT NOT NULL DEFAULT 0, limit_mbps_down INT NOT NULL DEFAULT 0, + xray_inbound_tag TEXT NOT NULL DEFAULT '', xray_protocol TEXT NOT NULL DEFAULT '', + price_cents INT NOT NULL DEFAULT 0, credit_cost INT NOT NULL DEFAULT 1, + server_id TEXT NOT NULL DEFAULT '', is_active BOOLEAN NOT NULL DEFAULT true, sort_order INT NOT NULL DEFAULT 0 +); + +CREATE TABLE IF NOT EXISTS bot_credit_packages ( + id SERIAL PRIMARY KEY, name TEXT NOT NULL DEFAULT '', credits INT NOT NULL DEFAULT 0, + price_cents INT NOT NULL DEFAULT 0, is_active BOOLEAN NOT NULL DEFAULT true, sort_order INT NOT NULL DEFAULT 0 +); + +CREATE TABLE IF NOT EXISTS bot_transactions ( + id SERIAL PRIMARY KEY, telegram_id BIGINT NOT NULL, type TEXT NOT NULL, + plan_id INT, package_id INT, credits INT NOT NULL DEFAULT 0, amount_cents INT NOT NULL DEFAULT 0, + mp_payment_id TEXT NOT NULL DEFAULT '', mp_qr_code TEXT NOT NULL DEFAULT '', mp_qr_base64 TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', target_username TEXT NOT NULL DEFAULT '', renew_target TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), paid_at TIMESTAMPTZ, expires_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS bot_transactions_mp_payment_id_uidx ON bot_transactions (mp_payment_id) WHERE mp_payment_id <> ''; + +CREATE TABLE IF NOT EXISTS bot_credits_ledger ( + id SERIAL PRIMARY KEY, telegram_id BIGINT NOT NULL, delta INT NOT NULL, reason TEXT NOT NULL DEFAULT '', + ref_transaction_id INT, balance_after INT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS bot_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL DEFAULT ''); + +CREATE TABLE IF NOT EXISTS bot_config ( + id INT PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT false, + telegram_mode TEXT NOT NULL DEFAULT 'polling', telegram_webhook_url TEXT NOT NULL DEFAULT '', + mp_confirm_mode TEXT NOT NULL DEFAULT 'polling', mp_poll_interval TEXT NOT NULL DEFAULT '20s', + pix_expiration_minutes INT NOT NULL DEFAULT 30, trial_enabled BOOLEAN NOT NULL DEFAULT true, + trial_hours INT NOT NULL DEFAULT 1, trial_max_connections INT NOT NULL DEFAULT 1, + trial_kind TEXT NOT NULL DEFAULT 'ssh', trial_inbound_tag TEXT NOT NULL DEFAULT '', + admin_telegram_ids BIGINT[] NOT NULL DEFAULT '{}', currency TEXT NOT NULL DEFAULT 'BRL', + public_host TEXT NOT NULL DEFAULT '', xray_public_host TEXT NOT NULL DEFAULT '', + telegram_token_enc BYTEA, telegram_webhook_secret_enc BYTEA, mp_access_token_enc BYTEA, mp_webhook_secret_enc BYTEA, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +INSERT INTO bot_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING; + +ALTER SCHEMA public OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS ssh_users OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS ssh_iface_totals OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS admin_users OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS xray_clients OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_users OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_plans OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_credit_packages OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_transactions OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_credits_ledger OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_settings OWNER TO ${DB_USER}; +ALTER TABLE IF EXISTS bot_config OWNER TO ${DB_USER}; +ALTER SEQUENCE IF EXISTS admin_users_id_seq OWNER TO ${DB_USER}; +GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER}; +GRANT ALL PRIVILEGES ON SCHEMA public TO ${DB_USER}; +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ${DB_USER}; +GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ${DB_USER}; +\"" postgres + +info " PostgreSQL database '${DB_NAME}' ready" + +# ── 8. Config files ────────────────────────────────────────────────────────── +info "[8/10] Generating config files…" + +# Admin token +ADMIN_TOKEN=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 48 || true) +if [[ ${#ADMIN_TOKEN} -lt 48 ]]; then + ADMIN_TOKEN=$(openssl rand -hex 24 2>/dev/null || date +%s%N) +fi + +# Preserve an admin account for API clients using session authentication. +ADMIN_PASSWORD=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20 || true) +if [[ ${#ADMIN_PASSWORD} -lt 20 ]]; then + ADMIN_PASSWORD=$(openssl rand -hex 10 2>/dev/null || date +%s%N) +fi +ADMIN_PASSWORD_HASH=$(printf '%s' "${ADMIN_PASSWORD}" | "$INSTALL_DIR/sshpanel" -hash-admin-password-stdin 2>/dev/null) +[[ "$ADMIN_PASSWORD_HASH" == \$2* ]] || error "Failed to generate admin bcrypt password hash" +su -c "psql -d ${DB_NAME}" postgres < "$INSTALL_DIR/.env" </dev/null \ + || curl -sf --max-time 5 https://api.ipify.org 2>/dev/null \ + || hostname -I | awk '{print $1}') + +# config.json +cat > "$INSTALL_DIR/config.json" </dev/null \ + || python3 -c "import uuid; print(uuid.uuid4())" 2>/dev/null \ + || echo "11111111-2222-3333-4444-555555555555") + +# xray_native_config.json is used by the internal emulator. xray_config.json is +# kept only for optional external-xray mode. Both start with the same default. +cat > "$INSTALL_DIR/xray_native_config.json" < 5300)…" +cat > /usr/local/sbin/sshpanel-dnstt-redirect.sh <<'EOS' +#!/bin/bash +set -euo pipefail +DNS_UPSTREAM="${DNS_UPSTREAM:-1.1.1.1}" +DNSTT_PORT="${DNSTT_PORT:-5300}" + +# Free port 53 on systemd-resolved based systems and keep outbound DNS working. +if command -v systemctl >/dev/null 2>&1; then + systemctl disable --now systemd-resolved.service >/dev/null 2>&1 || true +fi +rm -f /etc/resolv.conf +printf 'nameserver %s\n' "$DNS_UPSTREAM" > /etc/resolv.conf + +# Open DNS/UDP in common Linux firewalls when they are active. +if command -v ufw >/dev/null 2>&1; then + ufw allow 53/udp >/dev/null 2>&1 || true +fi +if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then + firewall-cmd --permanent --add-port=53/udp >/dev/null 2>&1 || true + firewall-cmd --reload >/dev/null 2>&1 || true +fi + +add_iptables_rule() { + local bin="$1" chain="$2" + "$bin" -t nat -C "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" 2>/dev/null \ + || "$bin" -t nat -A "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" +} + +if command -v iptables >/dev/null 2>&1; then + add_iptables_rule iptables PREROUTING +fi + +if command -v ip6tables >/dev/null 2>&1; then + add_iptables_rule ip6tables PREROUTING || true +fi + +# Fallback for minimal systems where only nft is present. +if ! command -v iptables >/dev/null 2>&1 && command -v nft >/dev/null 2>&1; then + nft add table inet sshpanel_nat 2>/dev/null || true + nft 'add chain inet sshpanel_nat prerouting { type nat hook prerouting priority dstnat; policy accept; }' 2>/dev/null || true + nft list chain inet sshpanel_nat prerouting 2>/dev/null | grep -q "udp dport 53 redirect to :$DNSTT_PORT" \ + || nft add rule inet sshpanel_nat prerouting udp dport 53 redirect to :"$DNSTT_PORT" +fi +EOS +chmod +x /usr/local/sbin/sshpanel-dnstt-redirect.sh + +cat > /etc/systemd/system/sshpanel-dnstt-redirect.service <<'EOF' +[Unit] +Description=SSH Panel DNSTT DNS redirect (UDP 53 to 5300) +After=network.target +Before=sshpanel.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/sshpanel-dnstt-redirect.sh +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +EOF + +"$SYSTEMCTL_BIN" daemon-reload +"$SYSTEMCTL_BIN" enable --now sshpanel-dnstt-redirect.service || warn "DNSTT DNS redirect service failed; check: journalctl -u sshpanel-dnstt-redirect -e" +info " DNSTT DNS redirect installed: UDP 53 -> 5300" + +# ── 10. Systemd service ────────────────────────────────────────────────────── +info "[10/10] Creating systemd service '${SERVICE_NAME}'…" +cat > "/etc/systemd/system/${SERVICE_NAME}.service" < len(data) { + end = len(data) + } + for index := offset; index < end; index++ { + out[index] = data[index] ^ key[index-offset] + } + } + return out +} + +func ReadRequest(reader io.Reader) (Request, error) { + var request Request + var header [HeaderSize]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return request, err + } + request.Mode = header[0] + if request.Mode > ModeLane { + return request, errors.New("unknown BHTTP mode") + } + copy(request.SID[:], header[1:17]) + request.Seq = binary.BigEndian.Uint64(header[17:25]) + request.Value = binary.BigEndian.Uint32(header[25:29]) + // Mode 2 overloads Value as a size hint. Mode 4 is an empty cumulative ACK. + if request.Mode == ModeDownload || request.Mode == ModeACK { + return request, nil + } + if request.Value > MaxPayload { + return request, errors.New("BHTTP request is too large") + } + if request.Value > 0 { + request.Payload = make([]byte, int(request.Value)) + if _, err := io.ReadFull(reader, request.Payload); err != nil { + return request, err + } + } + return request, nil +} + +func WriteStatus(writer io.Writer, status byte, data []byte) error { + packet := make([]byte, 5+len(data)) + packet[0] = status + binary.BigEndian.PutUint32(packet[1:5], uint32(len(data))) + copy(packet[5:], data) + return writeAll(writer, packet) +} + +func WriteDownload(writer io.Writer, sid SessionID, mode byte, seq uint64, data []byte) error { + encrypted := Crypt(data, sid, mode, seq, true) + packet := make([]byte, 9+len(encrypted)) + packet[0] = StatusData + binary.BigEndian.PutUint32(packet[1:5], uint32(4+len(encrypted))) + binary.BigEndian.PutUint32(packet[5:9], uint32(len(data))) + copy(packet[9:], encrypted) + return writeAll(writer, packet) +} + +func writeAll(writer io.Writer, data []byte) error { + for len(data) > 0 { + count, err := writer.Write(data) + if err != nil { + return err + } + if count <= 0 { + return io.ErrShortWrite + } + data = data[count:] + } + return nil +} diff --git a/internal/bhttp/protocol_test.go b/internal/bhttp/protocol_test.go new file mode 100644 index 0000000..e6dff27 --- /dev/null +++ b/internal/bhttp/protocol_test.go @@ -0,0 +1,256 @@ +package bhttp + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "io" + "net" + "testing" + "time" +) + +func TestCryptMatchesRestoredPythonServer(t *testing.T) { + var sid SessionID + for index := range sid { + sid[index] = byte(index) + } + tests := []struct { + clearHex string + mode byte + seq uint64 + response bool + wantHex string + }{ + {"42696c6f6c612d4248545450", 1, 0, false, "7ca4d6c962b839cf1fb68990"}, + {"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", 3, 123456789, true, "ccd73e4b14777caaa138d17c7016770da44fe50c4d7322a759298098a47230347567293f767bb2f8069a2ede76ac97ec5e031832b023b44f69918e02c6f313ea"}, + {"42485031010300000008", 0, 0, false, "1185931614521a40b889"}, + } + for _, test := range tests { + clear, _ := hex.DecodeString(test.clearHex) + want, _ := hex.DecodeString(test.wantHex) + got := Crypt(clear, sid, test.mode, test.seq, test.response) + if !bytes.Equal(got, want) { + t.Fatalf("mode=%d seq=%d got=%x want=%x", test.mode, test.seq, got, want) + } + if decoded := Crypt(got, sid, test.mode, test.seq, test.response); !bytes.Equal(decoded, clear) { + t.Fatalf("cipher did not round-trip mode=%d seq=%d", test.mode, test.seq) + } + } +} + +func writeTestRequest(writer io.Writer, mode byte, sid SessionID, sequence uint64, payload []byte, value uint32) error { + if mode != ModeDownload && mode != ModeACK { + value = uint32(len(payload)) + } + packet := make([]byte, HeaderSize+len(payload)) + packet[0] = mode + copy(packet[1:17], sid[:]) + binary.BigEndian.PutUint64(packet[17:25], sequence) + binary.BigEndian.PutUint32(packet[25:29], value) + copy(packet[29:], payload) + return writeAll(writer, packet) +} + +func readTestResponse(reader io.Reader) (byte, []byte, []byte, error) { + var header [5]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return 0, nil, nil, err + } + size := binary.BigEndian.Uint32(header[1:5]) + body := make([]byte, int(size)) + if _, err := io.ReadFull(reader, body); err != nil { + return 0, nil, nil, err + } + raw := append(append([]byte(nil), header[:]...), body...) + return header[0], body, raw, nil +} + +func waitBuffered(t *testing.T, session *Session, minimum int) { + t.Helper() + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + session.readyMu.Lock() + available := session.downloadBuffer.available() + session.readyMu.Unlock() + if available >= minimum { + return + } + time.Sleep(time.Millisecond) + } + t.Fatal("target bytes were not buffered") +} + +func TestServerSSHRelayBatchRetryAndACK(t *testing.T) { + targetServer, targetPeer := net.Pipe() + defer targetPeer.Close() + dialed := false + server := NewServer(Config{ + TargetAddress: "test:22", + DialTarget: func(address string) (net.Conn, error) { + if address != "test:22" || dialed { + t.Fatalf("unexpected target dial %q repeated=%v", address, dialed) + } + dialed = true + return targetServer, nil + }, + }) + defer server.Close() + + accepted, client := net.Pipe() + done := make(chan error, 1) + go func() { + done <- server.handleConnection(accepted) + accepted.Close() + }() + defer func() { + client.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("connection handler did not stop") + } + }() + _ = client.SetDeadline(time.Now().Add(3 * time.Second)) + + var sid SessionID + copy(sid[:], []byte("bilola-test-sid!")) + if err := writeTestRequest(client, ModeUpload, sid, 0, nil, 0); err != nil { + t.Fatal(err) + } + status, _, _, err := readTestResponse(client) + if err != nil || status != StatusOK { + t.Fatalf("registration status=%d err=%v", status, err) + } + session := server.sessions.GetOrCreate(sid) + + banner := []byte("SSH-2.0-BilolaGo\r\n") + go targetPeer.Write(banner) + waitBuffered(t, session, len(banner)) + if err := writeTestRequest(client, ModeDownload, sid, 0, nil, 65536); err != nil { + t.Fatal(err) + } + status, body, _, err := readTestResponse(client) + if err != nil || status != StatusData || len(body) < 4 { + t.Fatalf("banner response status=%d len=%d err=%v", status, len(body), err) + } + plainSize := int(binary.BigEndian.Uint32(body[:4])) + decoded := Crypt(body[4:], sid, ModeDownload, 0, true) + if plainSize != len(banner) || !bytes.Equal(decoded, banner) { + t.Fatalf("banner got=%q size=%d", decoded, plainSize) + } + + upload := []byte("SSH upload sequence zero") + encryptedUpload := Crypt(upload, sid, ModeUpload, 0, false) + targetUpload := make(chan []byte, 1) + go func() { + read := make([]byte, len(upload)) + if _, readErr := io.ReadFull(targetPeer, read); readErr != nil { + targetUpload <- nil + return + } + targetUpload <- read + }() + if err := writeTestRequest(client, ModeUpload, sid, 0, encryptedUpload, 0); err != nil { + t.Fatal(err) + } + status, _, _, err = readTestResponse(client) + if err != nil || status != StatusOK { + t.Fatalf("upload status=%d err=%v", status, err) + } + targetRead := <-targetUpload + if !bytes.Equal(targetRead, upload) { + t.Fatalf("target upload=%q", targetRead) + } + + downstream := make([]byte, 3000) + for index := range downstream { + downstream[index] = byte(index * 17) + } + go targetPeer.Write(downstream) + waitBuffered(t, session, len(downstream)) + batchClear := make([]byte, 6) + binary.BigEndian.PutUint32(batchClear[:4], 1399) + binary.BigEndian.PutUint16(batchClear[4:6], 3) + batchRequest := Crypt(batchClear, sid, ModeBatch, 1, false) + if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil { + t.Fatal(err) + } + var firstRaw [][]byte + var downloaded []byte + var raw []byte + for offset := 0; offset < 3; offset++ { + status, body, raw, err = readTestResponse(client) + if err != nil || status != StatusData || len(body) < 4 { + t.Fatalf("batch %d status=%d len=%d err=%v", offset, status, len(body), err) + } + plainSize = int(binary.BigEndian.Uint32(body[:4])) + decoded = Crypt(body[4:], sid, ModeBatch, 1+uint64(offset), true) + if len(decoded) != plainSize { + t.Fatalf("batch %d declared=%d decoded=%d", offset, plainSize, len(decoded)) + } + downloaded = append(downloaded, decoded...) + firstRaw = append(firstRaw, raw) + } + if !bytes.Equal(downloaded, downstream) { + t.Fatalf("batch data mismatch got=%d want=%d", len(downloaded), len(downstream)) + } + + if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil { + t.Fatal(err) + } + for offset := 0; offset < 3; offset++ { + _, _, raw, err := readTestResponse(client) + if err != nil || !bytes.Equal(raw, firstRaw[offset]) { + t.Fatalf("retry frame %d changed err=%v", offset, err) + } + } + + if err := writeTestRequest(client, ModeACK, sid, 3, nil, 0); err != nil { + t.Fatal(err) + } + status, _, _, err = readTestResponse(client) + if err != nil || status != StatusOK { + t.Fatalf("ACK status=%d err=%v", status, err) + } + session.downloadMu.Lock() + remaining := len(session.downloadFrames) + session.downloadMu.Unlock() + if remaining != 0 { + t.Fatalf("ACK retained %d replay frames", remaining) + } +} + +func TestProbeEchoMatchesBHP1(t *testing.T) { + server, client := net.Pipe() + done := make(chan error, 1) + go func() { + request, err := ReadRequest(server) + if err == nil { + err = handleProbe(server, request) + } + done <- err + server.Close() + }() + defer client.Close() + var sid SessionID + for index := range sid { + sid[index] = byte(index) + } + clear := []byte{'B', 'H', 'P', '1', 1, ModeDownload, 0, 0, 2, 0} + encrypted := Crypt(clear, sid, ModeProbe, 7, false) + if err := writeTestRequest(client, ModeProbe, sid, 7, encrypted, 0); err != nil { + t.Fatal(err) + } + status, body, _, err := readTestResponse(client) + if err != nil || status != StatusOK { + t.Fatalf("probe status=%d err=%v", status, err) + } + decoded := Crypt(body, sid, ModeProbe, 7, true) + if len(decoded) != 512 || !bytes.Equal(decoded[:10], clear) { + t.Fatalf("probe response len=%d prefix=%x", len(decoded), decoded[:10]) + } + if err := <-done; err != nil { + t.Fatal(err) + } +} diff --git a/internal/bhttp/server.go b/internal/bhttp/server.go new file mode 100644 index 0000000..ec4b945 --- /dev/null +++ b/internal/bhttp/server.go @@ -0,0 +1,589 @@ +package bhttp + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "strings" + "sync" + "sync/atomic" + "time" +) + +type Config struct { + TargetAddress string + SessionTimeout time.Duration + DialTimeout time.Duration + MaxV2Lanes int + Logger *log.Logger + DialTarget func(string) (net.Conn, error) + // MaxConnections caps concurrently accepted client sockets across every + // listener served by this server. Zero or negative disables the cap. + MaxConnections int + // MaxSessions caps concurrently tracked BHTTP sessions. Zero or negative + // disables the cap. A session is one logical tunnel; BHTTP v2 attaches + // several sockets ("lanes") to the same session. + MaxSessions int + // LogConnections enables one log line per accepted socket. Leave it off on + // busy servers. + LogConnections bool +} + +// StatsSnapshot is the counter set the admin panel reads. +type StatsSnapshot struct { + StartedAt time.Time `json:"startedAt"` + ActiveConnections int64 `json:"activeConnections"` + ActiveSessions int64 `json:"activeSessions"` + Accepted uint64 `json:"accepted"` + ConnectionsRejected uint64 `json:"connectionsRejected"` + SessionsRejected uint64 `json:"sessionsRejected"` + SessionsExpired uint64 `json:"sessionsExpired"` + Probes uint64 `json:"probes"` + ProbesV2 uint64 `json:"probesV2"` + HTTPUpgrades uint64 `json:"httpUpgrades"` + LanesAttached uint64 `json:"lanesAttached"` + LanesRejected uint64 `json:"lanesRejected"` + UploadBytes uint64 `json:"uploadBytes"` + DownloadBytes uint64 `json:"downloadBytes"` + TargetFailures uint64 `json:"targetFailures"` + ProtocolErrors uint64 `json:"protocolErrors"` +} + +type counters struct { + accepted atomic.Uint64 + connectionsRejected atomic.Uint64 + sessionsRejected atomic.Uint64 + sessionsExpired atomic.Uint64 + probes atomic.Uint64 + probesV2 atomic.Uint64 + httpUpgrades atomic.Uint64 + lanesAttached atomic.Uint64 + lanesRejected atomic.Uint64 + uploadBytes atomic.Uint64 + downloadBytes atomic.Uint64 + targetFailures atomic.Uint64 + protocolErrors atomic.Uint64 + activeConnections atomic.Int64 +} + +type Server struct { + config Config + sessions *SessionManager + closed chan struct{} + once sync.Once + wait sync.WaitGroup + connMu sync.Mutex + active map[net.Conn]struct{} + started time.Time + stats counters +} + +const ( + bhttpV2Version = 2 + bhttpV2FeatureLanes = 1 << 0 + bhttpV2FeatureResume = 1 << 1 + bhttpV2FeatureAck = 1 << 2 + bhttpV2MaxLanes = 128 + laneUpload = 1 + laneDownload = 2 + laneDuplex = 3 +) + +func NewServer(config Config) *Server { + if config.TargetAddress == "" { + config.TargetAddress = "127.0.0.1:22" + } + if config.SessionTimeout <= 0 { + config.SessionTimeout = 2 * time.Minute + } + if config.DialTimeout <= 0 { + config.DialTimeout = 10 * time.Second + } + if config.MaxV2Lanes <= 0 { + config.MaxV2Lanes = bhttpV2MaxLanes + } + if config.Logger == nil { + config.Logger = log.Default() + } + if config.DialTarget == nil { + dialer := net.Dialer{Timeout: config.DialTimeout, KeepAlive: 30 * time.Second} + config.DialTarget = func(address string) (net.Conn, error) { + connection, err := dialer.Dial("tcp", address) + if err == nil { + if tcp, ok := connection.(*net.TCPConn); ok { + _ = tcp.SetNoDelay(true) + } + } + return connection, err + } + } + server := &Server{ + config: config, + sessions: NewSessionManager(config.SessionTimeout), + closed: make(chan struct{}), + active: make(map[net.Conn]struct{}), + started: time.Now(), + } + server.sessions.limit = config.MaxSessions + server.sessions.rejected = &server.stats.sessionsRejected + server.wait.Add(1) + go server.cleanupLoop() + return server +} + +func (server *Server) cleanupLoop() { + defer server.wait.Done() + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + removed := server.sessions.Cleanup(now) + if removed > 0 { + server.stats.sessionsExpired.Add(uint64(removed)) + server.config.Logger.Printf("cleaned %d stale BHTTP sessions", removed) + } + case <-server.closed: + return + } + } +} + +func (server *Server) Serve(listener net.Listener) error { + for { + connection, err := listener.Accept() + if err != nil { + select { + case <-server.closed: + return nil + default: + return err + } + } + if tcp, ok := connection.(*net.TCPConn); ok { + _ = tcp.SetNoDelay(true) + } + server.stats.accepted.Add(1) + if !server.track(connection) { + continue + } + server.wait.Add(1) + go func() { + defer server.wait.Done() + server.run(connection) + }() + } +} + +// ServeConn serves one already-accepted connection, for listeners this server +// does not own. A port shared with SSH or HTTP routes a client here once the +// first bytes have been identified as BHTTP; the connection is then counted, +// capped and closed exactly like one from Serve's own accept loop. +// +// It blocks until the connection ends. It reports whether the connection was +// admitted: a refused connection has already been closed, and the caller must +// not keep using it either way. +func (server *Server) ServeConn(connection net.Conn) bool { + select { + case <-server.closed: + _ = connection.Close() + return false + default: + } + server.stats.accepted.Add(1) + if !server.track(connection) { + return false + } + server.wait.Add(1) + defer server.wait.Done() + server.run(connection) + return true +} + +// track registers a connection against the socket cap. It reports whether the +// connection was admitted; a rejected connection is closed here. +func (server *Server) track(connection net.Conn) bool { + server.connMu.Lock() + // Reject past the socket cap before any protocol work, so a surge cannot + // exhaust memory the way an unbounded accept loop would. + if limit := server.config.MaxConnections; limit > 0 && len(server.active) >= limit { + server.connMu.Unlock() + rejected := server.stats.connectionsRejected.Add(1) + if rejected == 1 || rejected%1000 == 0 { + server.config.Logger.Printf("connection cap reached (%d); rejected %d client(s) so far", + limit, rejected) + } + _ = connection.Close() + return false + } + server.active[connection] = struct{}{} + server.connMu.Unlock() + server.stats.activeConnections.Add(1) + if server.config.LogConnections { + server.config.Logger.Printf("client %s connected", connection.RemoteAddr()) + } + return true +} + +// run drives one tracked connection to completion and releases it. +func (server *Server) run(connection net.Conn) { + defer func() { + server.connMu.Lock() + delete(server.active, connection) + server.connMu.Unlock() + server.stats.activeConnections.Add(-1) + _ = connection.Close() + if server.config.LogConnections { + server.config.Logger.Printf("client %s disconnected", connection.RemoteAddr()) + } + }() + if err := server.handleConnection(connection); err != nil && !isNormalClose(err) { + server.stats.protocolErrors.Add(1) + server.config.Logger.Printf("client %s: %v", connection.RemoteAddr(), err) + } +} + +func isNormalClose(err error) bool { + return errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) || strings.Contains(err.Error(), "connection reset") +} + +func (server *Server) handleConnection(connection net.Conn) error { + reader := bufio.NewReader(connection) + first, err := reader.Peek(1) + if err != nil { + return err + } + if first[0] == ModeProbe { + request, err := ReadRequest(reader) + if err != nil { + return err + } + server.stats.probes.Add(1) + if isV2Probe(request) { + server.stats.probesV2.Add(1) + } + return handleProbeLimit(connection, request, server.config.MaxV2Lanes) + } + if first[0] > ModeLane { + if err := handleHTTPUpgrade(reader, connection); err != nil { + return err + } + server.stats.httpUpgrades.Add(1) + } + var laneRole byte + var laneLease *LaneLease + defer func() { + if laneLease != nil { + laneLease.ReleaseLane() + } + }() + for { + request, err := ReadRequest(reader) + if err != nil { + return err + } + if request.Mode == ModeLane { + if laneLease != nil { + return errors.New("BHTTP v2 lane already attached") + } + role, attached, attachErr := server.attachLane(connection, request) + if attachErr != nil { + return attachErr + } + laneRole = role + laneLease = attached + continue + } + if laneRole == laneUpload && request.Mode != ModeUpload { + return errors.New("BHTTP v2 upload lane received non-upload request") + } + if laneRole == laneDownload && request.Mode != ModeDownload && + request.Mode != ModeBatch && request.Mode != ModeACK { + return errors.New("BHTTP v2 download lane received invalid request") + } + session := server.sessions.GetOrCreate(request.SID) + if session == nil { + _ = WriteStatus(connection, StatusError, []byte("BHTTP session limit reached")) + return errors.New("BHTTP session limit reached") + } + session.touch() + if err := server.handleRequest(connection, session, request, laneRole != 0); err != nil { + return err + } + } +} + +func handleHTTPUpgrade(reader *bufio.Reader, writer io.Writer) error { + var request bytes.Buffer + for request.Len() < 64*1024 { + value, err := reader.ReadByte() + if err != nil { + return err + } + request.WriteByte(value) + if bytes.HasSuffix(request.Bytes(), []byte("\r\n\r\n")) { + return writeAll(writer, []byte("HTTP/1.1 101 DTunnel\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\nHTTP/1.1 200 DTunnel\r\n\r\n")) + } + } + return errors.New("HTTP upgrade header is too large") +} + +// isV2Probe reports whether a probe payload announces the BHP2 capability +// handshake rather than the original BHP1 profile. +func isV2Probe(request Request) bool { + clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false) + return len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version +} + +// Stats returns a snapshot of the server counters for the admin panel. +func (server *Server) Stats() StatsSnapshot { + return StatsSnapshot{ + StartedAt: server.started, + ActiveConnections: server.stats.activeConnections.Load(), + ActiveSessions: int64(server.sessions.Len()), + Accepted: server.stats.accepted.Load(), + ConnectionsRejected: server.stats.connectionsRejected.Load(), + SessionsRejected: server.stats.sessionsRejected.Load(), + SessionsExpired: server.stats.sessionsExpired.Load(), + Probes: server.stats.probes.Load(), + ProbesV2: server.stats.probesV2.Load(), + HTTPUpgrades: server.stats.httpUpgrades.Load(), + LanesAttached: server.stats.lanesAttached.Load(), + LanesRejected: server.stats.lanesRejected.Load(), + UploadBytes: server.stats.uploadBytes.Load(), + DownloadBytes: server.stats.downloadBytes.Load(), + TargetFailures: server.stats.targetFailures.Load(), + ProtocolErrors: server.stats.protocolErrors.Load(), + } +} + +func handleProbe(writer io.Writer, request Request) error { + return handleProbeLimit(writer, request, bhttpV2MaxLanes) +} + +func handleProbeLimit(writer io.Writer, request Request, maxLanes int) error { + clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false) + if len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version { + response := make([]byte, 14) + copy(response[:4], []byte("BHP2")) + response[4] = bhttpV2Version + binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck) + binary.BigEndian.PutUint32(response[10:14], uint32(maxLanes)) + return WriteStatus(writer, StatusOK, Crypt(response, request.SID, ModeProbe, request.Seq, true)) + } + if len(clear) < 10 || !bytes.Equal(clear[:4], []byte("BHP1")) || clear[4] != 1 { + return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe")) + } + submode := clear[5] + parameter := int(binary.BigEndian.Uint32(clear[6:10])) + if submode > ModeACK { + return WriteStatus(writer, StatusError, []byte("unsupported BHTTP probe mode")) + } + expected := 10 + if submode == ModeUpload && parameter >= 10 { + expected = parameter + } + if len(clear) != expected { + return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe length")) + } + for index := 10; index < len(clear); index++ { + if clear[index] != byte(index*31) { + return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe pattern")) + } + } + responseSize := 10 + if submode == ModeDownload && parameter > responseSize { + responseSize = parameter + } + if responseSize > MaxPayload { + return WriteStatus(writer, StatusError, []byte("BHTTP v1 probe too large")) + } + response := make([]byte, responseSize) + copy(response[:4], []byte("BHP1")) + response[4] = 1 + response[5] = submode + binary.BigEndian.PutUint32(response[6:10], uint32(parameter)) + for index := 10; index < len(response); index++ { + response[index] = byte(index * 31) + } + encrypted := Crypt(response, request.SID, ModeProbe, request.Seq, true) + count := 1 + if submode == ModeACK { + count = parameter + if count < 1 { + count = 1 + } + if count > 256 { + count = 256 + } + } + for index := 0; index < count; index++ { + if err := WriteStatus(writer, StatusOK, encrypted); err != nil { + return err + } + } + return nil +} + +func (server *Server) handleRequest(writer io.Writer, session *Session, request Request, version2 bool) error { + switch request.Mode { + case ModeUpload: + payload := request.Payload + if len(payload) > 0 { + payload = Crypt(payload, request.SID, request.Mode, request.Seq, false) + } + if request.Seq == 0 && len(payload) == 0 { + if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil { + server.stats.targetFailures.Add(1) + return WriteStatus(writer, StatusError, []byte("SSH target unavailable")) + } + return WriteStatus(writer, StatusOK, nil) + } + if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil { + server.stats.targetFailures.Add(1) + return WriteStatus(writer, StatusError, []byte("SSH target unavailable")) + } + if err := session.WriteUpload(request.Seq, payload); err != nil { + return WriteStatus(writer, StatusError, []byte("SSH upload failed")) + } + server.stats.uploadBytes.Add(uint64(len(payload))) + if !version2 { + return WriteStatus(writer, StatusOK, nil) + } + ack := make([]byte, 9) + if sequence, ok := session.UploadCommitted(); ok { + ack[0] = 1 + binary.BigEndian.PutUint64(ack[1:], sequence) + } + return WriteStatus(writer, StatusOK, ack) + + case ModeDownload: + chunks := session.AssignDownload(request.Seq, 1, 65536) + server.stats.downloadBytes.Add(uint64(len(chunks[0]))) + return WriteDownload(writer, request.SID, request.Mode, request.Seq, chunks[0]) + + case ModeBatch: + clear := Crypt(request.Payload, request.SID, request.Mode, request.Seq, false) + if len(clear) != 6 { + return WriteStatus(writer, StatusError, []byte("invalid BHTTP batch request")) + } + limit := int(binary.BigEndian.Uint32(clear[:4])) + count := int(binary.BigEndian.Uint16(clear[4:6])) + if limit < 1 { + limit = 1 + } + if limit > MaxDownloadSize { + limit = MaxDownloadSize + } + if count < 1 { + count = 1 + } + if count > 256 { + count = 256 + } + chunks := session.AssignDownload(request.Seq, count, limit) + for offset, chunk := range chunks { + server.stats.downloadBytes.Add(uint64(len(chunk))) + if err := WriteDownload(writer, request.SID, request.Mode, request.Seq+uint64(offset), chunk); err != nil { + return err + } + } + return nil + + case ModeACK: + session.Acknowledge(request.Seq) + return WriteStatus(writer, StatusOK, nil) + } + return fmt.Errorf("unsupported BHTTP mode %d", request.Mode) +} + +func (server *Server) attachLane(writer io.Writer, request Request) (byte, *LaneLease, error) { + clear := Crypt(request.Payload, request.SID, ModeLane, request.Seq, false) + if len(clear) != 12 || !bytes.Equal(clear[:4], []byte("BLN2")) || clear[4] != bhttpV2Version { + server.stats.lanesRejected.Add(1) + _ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane hello")) + return 0, nil, errors.New("invalid BHTTP v2 lane hello") + } + role := clear[5] + if role != laneUpload && role != laneDownload && role != laneDuplex { + server.stats.lanesRejected.Add(1) + _ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane role")) + return 0, nil, errors.New("invalid BHTTP v2 lane role") + } + requireResume := binary.BigEndian.Uint16(clear[6:8])&1 != 0 + laneID := binary.BigEndian.Uint32(clear[8:12]) + session, resumed := server.sessions.Get(request.SID) + if requireResume && !resumed { + server.stats.lanesRejected.Add(1) + _ = WriteStatus(writer, StatusError, []byte("BHTTP v2 session expired")) + return 0, nil, errors.New("BHTTP v2 resume rejected: session expired") + } + if !resumed { + session, _ = server.sessions.GetOrCreateState(request.SID) + if session == nil { + server.stats.lanesRejected.Add(1) + _ = WriteStatus(writer, StatusError, []byte("BHTTP session limit reached")) + return 0, nil, errors.New("BHTTP session limit reached") + } + } + lease, acquired := session.AcquireLane(laneID, server.config.MaxV2Lanes) + if !acquired { + server.stats.lanesRejected.Add(1) + _ = WriteStatus(writer, StatusError, []byte("BHTTP v2 lane limit exceeded")) + return 0, nil, errors.New("BHTTP v2 lane limit exceeded") + } + attached := true + defer func() { + if attached { + lease.ReleaseLane() + } + }() + if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil { + server.stats.targetFailures.Add(1) + _ = WriteStatus(writer, StatusError, []byte("SSH target unavailable")) + return 0, nil, err + } + response := make([]byte, 18) + copy(response[:4], []byte("BOK2")) + response[4] = bhttpV2Version + if resumed { + response[5] = 1 + } + binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck) + if sequence, ok := session.UploadCommitted(); ok { + binary.BigEndian.PutUint64(response[10:18], sequence+1) + } + encoded := Crypt(response, request.SID, ModeLane, request.Seq, true) + if err := WriteStatus(writer, StatusOK, encoded); err != nil { + return 0, nil, err + } + session.touch() + attached = false + server.stats.lanesAttached.Add(1) + return role, lease, nil +} + +func (server *Server) Close() { + server.once.Do(func() { + close(server.closed) + server.connMu.Lock() + connections := make([]net.Conn, 0, len(server.active)) + for connection := range server.active { + connections = append(connections, connection) + } + server.connMu.Unlock() + for _, connection := range connections { + _ = connection.Close() + } + server.sessions.Close() + }) +} + +func (server *Server) Wait() { + server.wait.Wait() +} diff --git a/internal/bhttp/session.go b/internal/bhttp/session.go new file mode 100644 index 0000000..ea7a180 --- /dev/null +++ b/internal/bhttp/session.go @@ -0,0 +1,415 @@ +package bhttp + +import ( + "errors" + "io" + "net" + "sync" + "sync/atomic" + "time" +) + +type byteQueue struct { + data []byte + offset int +} + +func (queue *byteQueue) append(data []byte) { + queue.data = append(queue.data, data...) +} + +func (queue *byteQueue) available() int { + return len(queue.data) - queue.offset +} + +func (queue *byteQueue) take(limit int) []byte { + if queue.available() == 0 { + return nil + } + end := queue.offset + limit + if end > len(queue.data) { + end = len(queue.data) + } + out := append([]byte(nil), queue.data[queue.offset:end]...) + queue.offset = end + if queue.offset == len(queue.data) { + queue.data = queue.data[:0] + queue.offset = 0 + } else if queue.offset >= 1<<20 && queue.offset*2 >= len(queue.data) { + copy(queue.data, queue.data[queue.offset:]) + queue.data = queue.data[:len(queue.data)-queue.offset] + queue.offset = 0 + } + return out +} + +type Session struct { + sid SessionID + + openOnce sync.Once + openErr error + target net.Conn + + uploadMu sync.Mutex + uploadPending map[uint64][]byte + uploadNext uint64 + laneMu sync.Mutex + activeLanes map[uint32]uint64 + nextLaneLease uint64 + + readyMu sync.Mutex + readySignal chan struct{} + downloadBuffer byteQueue + bannerDelivered bool + targetEOF bool + targetError error + + downloadMu sync.Mutex + downloadSignal chan struct{} + downloadNext uint64 + downloadAcked uint64 + hasACK bool + downloadClosed bool + downloadFrames map[uint64][]byte + + lastSeen atomic.Int64 + closeOnce sync.Once +} + +type LaneLease struct { + session *Session + laneID uint32 + generation uint64 + once sync.Once +} + +// AcquireLane gives a stable lane ID a new generation. Reconnecting the same +// logical lane replaces its previous socket immediately instead of consuming +// another slot until the old handler notices the close. +func (session *Session) AcquireLane(laneID uint32, maximum int) (*LaneLease, bool) { + session.laneMu.Lock() + defer session.laneMu.Unlock() + if _, replacing := session.activeLanes[laneID]; !replacing && + maximum > 0 && len(session.activeLanes) >= maximum { + return nil, false + } + session.nextLaneLease++ + generation := session.nextLaneLease + session.activeLanes[laneID] = generation + return &LaneLease{session: session, laneID: laneID, generation: generation}, true +} + +func (lease *LaneLease) ReleaseLane() { + if lease == nil || lease.session == nil { + return + } + lease.once.Do(func() { + lease.session.laneMu.Lock() + if lease.session.activeLanes[lease.laneID] == lease.generation { + delete(lease.session.activeLanes, lease.laneID) + } + lease.session.laneMu.Unlock() + }) +} + +func NewSession(sid SessionID) *Session { + session := &Session{ + sid: sid, + uploadPending: make(map[uint64][]byte), + activeLanes: make(map[uint32]uint64), + readySignal: make(chan struct{}), + downloadSignal: make(chan struct{}), + downloadFrames: make(map[uint64][]byte), + } + session.touch() + return session +} + +func (session *Session) touch() { + session.lastSeen.Store(time.Now().UnixNano()) +} + +func (session *Session) LastSeen() time.Time { + return time.Unix(0, session.lastSeen.Load()) +} + +func (session *Session) signalReadyLocked() { + close(session.readySignal) + session.readySignal = make(chan struct{}) +} + +func (session *Session) signalDownloadLocked() { + close(session.downloadSignal) + session.downloadSignal = make(chan struct{}) +} + +func (session *Session) OpenTarget(address string, dialer func(string) (net.Conn, error)) error { + session.openOnce.Do(func() { + target, err := dialer(address) + if err != nil { + session.openErr = err + session.readyMu.Lock() + session.targetError = err + session.targetEOF = true + session.signalReadyLocked() + session.readyMu.Unlock() + return + } + session.target = target + go session.readTarget() + }) + return session.openErr +} + +func (session *Session) readTarget() { + buffer := make([]byte, 65536) + for { + count, err := session.target.Read(buffer) + if count > 0 { + session.readyMu.Lock() + session.downloadBuffer.append(buffer[:count]) + session.touch() + session.signalReadyLocked() + session.readyMu.Unlock() + } + if err != nil { + session.readyMu.Lock() + if !errors.Is(err, io.EOF) { + session.targetError = err + } + session.targetEOF = true + session.signalReadyLocked() + session.readyMu.Unlock() + + session.downloadMu.Lock() + session.downloadClosed = true + session.signalDownloadLocked() + session.downloadMu.Unlock() + return + } + } +} + +func (session *Session) WriteUpload(sequence uint64, payload []byte) error { + session.uploadMu.Lock() + defer session.uploadMu.Unlock() + if sequence < session.uploadNext { + return nil + } + if _, exists := session.uploadPending[sequence]; !exists { + session.uploadPending[sequence] = append([]byte(nil), payload...) + } + for { + chunk, exists := session.uploadPending[session.uploadNext] + if !exists { + return nil + } + delete(session.uploadPending, session.uploadNext) + if len(chunk) > 0 && session.target != nil { + if err := writeAll(session.target, chunk); err != nil { + return err + } + } + session.uploadNext++ + session.touch() + } +} + +// UploadCommitted reports the highest contiguous upload sequence written to +// the target. Receipt alone is not a commit when lanes arrive out of order. +func (session *Session) UploadCommitted() (uint64, bool) { + session.uploadMu.Lock() + defer session.uploadMu.Unlock() + if session.uploadNext == 0 { + return 0, false + } + return session.uploadNext - 1, true +} + +func (session *Session) TakeDownload(sequence uint64, limit int, bannerTimeout time.Duration) []byte { + if limit < 1 { + limit = 1 + } + if limit > MaxDownloadSize { + limit = MaxDownloadSize + } + deadline := time.NewTimer(bannerTimeout) + defer deadline.Stop() + + session.readyMu.Lock() + defer session.readyMu.Unlock() + if !session.bannerDelivered && sequence != 0 { + return nil + } + for session.downloadBuffer.available() == 0 && !session.targetEOF { + if session.bannerDelivered { + return nil + } + signal := session.readySignal + session.readyMu.Unlock() + select { + case <-signal: + case <-deadline.C: + session.readyMu.Lock() + return nil + } + session.readyMu.Lock() + } + chunk := session.downloadBuffer.take(limit) + if len(chunk) == 0 { + return nil + } + session.bannerDelivered = true + session.touch() + return chunk +} + +func (session *Session) AssignDownload(sequence uint64, count int, limit int) [][]byte { + session.downloadMu.Lock() + for sequence > session.downloadNext && !session.downloadClosed { + signal := session.downloadSignal + session.downloadMu.Unlock() + <-signal + session.downloadMu.Lock() + } + isNew := sequence == session.downloadNext + chunks := make([][]byte, count) + for offset := 0; offset < count; offset++ { + current := sequence + uint64(offset) + if isNew { + chunk := session.TakeDownload(current, limit, 5*time.Second) + if len(chunk) > 0 { + session.downloadFrames[current] = chunk + } + chunks[offset] = chunk + } else { + chunks[offset] = append([]byte(nil), session.downloadFrames[current]...) + } + } + if isNew { + session.downloadNext += uint64(count) + session.signalDownloadLocked() + } + session.downloadMu.Unlock() + return chunks +} + +func (session *Session) Acknowledge(sequence uint64) { + session.downloadMu.Lock() + defer session.downloadMu.Unlock() + if session.hasACK && sequence <= session.downloadAcked { + return + } + session.hasACK = true + session.downloadAcked = sequence + for number := range session.downloadFrames { + if number <= sequence { + delete(session.downloadFrames, number) + } + } +} + +func (session *Session) Close() { + session.closeOnce.Do(func() { + if session.target != nil { + _ = session.target.Close() + } + session.readyMu.Lock() + session.targetEOF = true + session.signalReadyLocked() + session.readyMu.Unlock() + session.downloadMu.Lock() + session.downloadClosed = true + session.signalDownloadLocked() + session.downloadMu.Unlock() + }) +} + +type SessionManager struct { + mu sync.RWMutex + sessions map[SessionID]*Session + timeout time.Duration + // limit caps concurrently tracked sessions. Zero or negative disables it. + limit int + // rejected, when set, counts sessions turned away at the limit. + rejected *atomic.Uint64 +} + +func NewSessionManager(timeout time.Duration) *SessionManager { + return &SessionManager{sessions: make(map[SessionID]*Session), timeout: timeout} +} + +// GetOrCreate returns the session for sid, creating it if needed. It returns +// nil when the session limit is already reached and sid is not known yet. +func (manager *SessionManager) GetOrCreate(sid SessionID) *Session { + session, _ := manager.GetOrCreateState(sid) + return session +} + +// GetOrCreateState reports whether the returned session already existed. A nil +// session means the manager is at its configured limit. +func (manager *SessionManager) GetOrCreateState(sid SessionID) (*Session, bool) { + manager.mu.RLock() + session := manager.sessions[sid] + manager.mu.RUnlock() + if session != nil { + return session, true + } + manager.mu.Lock() + defer manager.mu.Unlock() + if session = manager.sessions[sid]; session != nil { + return session, true + } + if manager.limit > 0 && len(manager.sessions) >= manager.limit { + if manager.rejected != nil { + manager.rejected.Add(1) + } + return nil, false + } + session = NewSession(sid) + manager.sessions[sid] = session + return session, false +} + +// Len reports how many sessions are currently tracked. +func (manager *SessionManager) Len() int { + manager.mu.RLock() + defer manager.mu.RUnlock() + return len(manager.sessions) +} + +func (manager *SessionManager) Get(sid SessionID) (*Session, bool) { + manager.mu.RLock() + session := manager.sessions[sid] + manager.mu.RUnlock() + return session, session != nil +} + +func (manager *SessionManager) Cleanup(now time.Time) int { + manager.mu.Lock() + var stale []*Session + for sid, session := range manager.sessions { + if now.Sub(session.LastSeen()) > manager.timeout { + delete(manager.sessions, sid) + stale = append(stale, session) + } + } + manager.mu.Unlock() + for _, session := range stale { + session.Close() + } + return len(stale) +} + +func (manager *SessionManager) Close() { + manager.mu.Lock() + sessions := make([]*Session, 0, len(manager.sessions)) + for sid, session := range manager.sessions { + delete(manager.sessions, sid) + sessions = append(sessions, session) + } + manager.mu.Unlock() + for _, session := range sessions { + session.Close() + } +} diff --git a/internal/bhttp/sniff.go b/internal/bhttp/sniff.go new file mode 100644 index 0000000..e3f166c --- /dev/null +++ b/internal/bhttp/sniff.go @@ -0,0 +1,99 @@ +package bhttp + +import ( + "bytes" + "encoding/binary" +) + +// Verdict is the result of inspecting the first bytes of a connection. +type Verdict int + +const ( + // VerdictNo means the bytes cannot begin a BHTTP frame. + VerdictNo Verdict = iota + // VerdictMore means the bytes so far are consistent with BHTTP but more + // are needed to decide. The caller should peek further and ask again. + VerdictMore + // VerdictYes means the bytes begin a BHTTP frame. + VerdictYes +) + +// SniffLimit is the largest number of bytes SniffFrame will ever ask for. It +// covers a full frame header plus a probe/lane payload, which is where the +// magic strings that make the decision conclusive live. +const SniffLimit = HeaderSize + 4096 + +// SniffFrame reports whether data begins a BHTTP frame, so a listener shared +// with other protocols can route the connection without consuming anything. +// +// The first byte alone already separates BHTTP from the protocols it shares a +// port with: a BHTTP frame opens with a mode number (0..5), while SSH opens +// with 'S' (0x53) and an HTTP request or status line opens with a method or +// version letter. Every one of those is far above ModeLane, so a single byte +// rejects them outright and costs nothing. +// +// A low first byte is not proof on its own, because HTTP-injection clients may +// prepend arbitrary junk. So the frame header is range-checked, and for the two +// modes that carry a magic string — the probe that opens every client session +// and the v2 lane hello — the magic is decrypted and verified. That check is +// keyed by the session ID in the same header, so junk cannot pass it by chance. +func SniffFrame(data []byte) Verdict { + if len(data) == 0 { + return VerdictMore + } + mode := data[0] + if mode > ModeLane { + return VerdictNo + } + if len(data) < HeaderSize { + return VerdictMore + } + + request := Request{Mode: mode} + copy(request.SID[:], data[1:17]) + request.Seq = binary.BigEndian.Uint64(data[17:25]) + request.Value = binary.BigEndian.Uint32(data[25:29]) + + // Modes 2 and 4 overload Value as a size hint and an empty cumulative ACK, + // so they carry no payload to verify. + if mode == ModeDownload || mode == ModeACK { + return VerdictYes + } + if request.Value > MaxPayload { + return VerdictNo + } + + magic, ok := frameMagic(mode) + if !ok { + // Modes 1 and 3 have no magic string. A sane header is all there is. + return VerdictYes + } + // An oversized payload cannot be a probe or lane hello, both of which are + // short, so the magic would not be where it belongs. + if int(request.Value) > SniffLimit-HeaderSize { + return VerdictNo + } + end := HeaderSize + int(request.Value) + if len(data) < end { + return VerdictMore + } + clear := Crypt(data[HeaderSize:end], request.SID, mode, request.Seq, false) + if len(clear) < len(magic) || !bytes.Equal(clear[:len(magic)], magic) { + return VerdictNo + } + return VerdictYes +} + +// frameMagic returns the plaintext prefix a mode's payload must start with, +// and whether that mode has one at all. +func frameMagic(mode byte) ([]byte, bool) { + switch mode { + case ModeProbe: + // A probe is either the BHP1 profile or the BHP2 capability handshake; + // both share the first three bytes, which is what is checked here. + return []byte("BHP"), true + case ModeLane: + return []byte("BLN2"), true + } + return nil, false +} diff --git a/internal/bhttp/sniff_test.go b/internal/bhttp/sniff_test.go new file mode 100644 index 0000000..0bd4929 --- /dev/null +++ b/internal/bhttp/sniff_test.go @@ -0,0 +1,164 @@ +package bhttp + +import ( + "encoding/binary" + "testing" +) + +// frame builds a wire frame for the sniffer to inspect. +func frame(mode byte, sid SessionID, sequence uint64, clear []byte) []byte { + payload := Crypt(clear, sid, mode, sequence, false) + out := make([]byte, HeaderSize+len(payload)) + out[0] = mode + copy(out[1:17], sid[:]) + binary.BigEndian.PutUint64(out[17:25], sequence) + binary.BigEndian.PutUint32(out[25:29], uint32(len(payload))) + copy(out[HeaderSize:], payload) + return out +} + +func probeClear(magic string, submode byte, parameter uint32) []byte { + clear := make([]byte, 10) + copy(clear[:4], magic) + clear[4] = 1 + clear[5] = submode + binary.BigEndian.PutUint32(clear[6:10], parameter) + return clear +} + +// Everything BHTTP shares a port with has to be rejected on the first byte, +// otherwise sharing the port would break SSH and HTTP-injection clients. +func TestSniffRejectsTheProtocolsItSharesPortsWith(t *testing.T) { + tests := map[string]string{ + "SSH identification": "SSH-2.0-OpenSSH_9.6\r\n", + "HTTP GET": "GET / HTTP/1.1\r\nHost: x\r\n\r\n", + "HTTP POST": "POST /path HTTP/1.1\r\n\r\n", + "HTTP HEAD": "HEAD / HTTP/1.0\r\n\r\n", + "HTTP CONNECT": "CONNECT host:443 HTTP/1.1\r\n\r\n", + "HTTP OPTIONS": "OPTIONS / HTTP/1.1\r\n\r\n", + "HTTP PATCH": "PATCH / HTTP/1.1\r\n\r\n", + "HTTP status line": "HTTP/1.1 200 OK\r\n\r\n", + "TLS client hello": "\x16\x03\x01\x02\x00\x01\x00\x01\xfc\x03\x03", + "bare CRLF": "\r\n\r\n", + } + for name, input := range tests { + t.Run(name, func(t *testing.T) { + if got := SniffFrame([]byte(input)); got != VerdictNo { + t.Fatalf("SniffFrame(%q) = %v, want VerdictNo", input, got) + } + }) + } +} + +func TestSniffAcceptsProbeFrames(t *testing.T) { + var sid SessionID + copy(sid[:], "sniff-probe-sid1") + + bhp1 := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0)) + if got := SniffFrame(bhp1); got != VerdictYes { + t.Fatalf("BHP1 probe = %v, want VerdictYes", got) + } + + capability := make([]byte, 10) + copy(capability[:4], "BHP2") + capability[4] = 2 + bhp2 := frame(ModeProbe, sid, 3, capability) + if got := SniffFrame(bhp2); got != VerdictYes { + t.Fatalf("BHP2 probe = %v, want VerdictYes", got) + } +} + +func TestSniffAcceptsLaneAndDataFrames(t *testing.T) { + var sid SessionID + copy(sid[:], "sniff-lane-sid01") + + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneUpload + binary.BigEndian.PutUint32(hello[8:], 4) + if got := SniffFrame(frame(ModeLane, sid, 9, hello)); got != VerdictYes { + t.Fatalf("v2 lane hello = %v, want VerdictYes", got) + } + + // Modes 2 and 4 carry no payload; a sane header is the whole signal. + if got := SniffFrame(frame(ModeDownload, sid, 1, nil)); got != VerdictYes { + t.Fatalf("download frame = %v, want VerdictYes", got) + } + if got := SniffFrame(frame(ModeACK, sid, 2, nil)); got != VerdictYes { + t.Fatalf("ACK frame = %v, want VerdictYes", got) + } + if got := SniffFrame(frame(ModeUpload, sid, 0, nil)); got != VerdictYes { + t.Fatalf("session-open upload frame = %v, want VerdictYes", got) + } +} + +// An injection client may prepend arbitrary junk, and some of that junk starts +// with a low byte. The magic check on the frame types that carry one is what +// keeps such a connection out of BHTTP. +func TestSniffRejectsLowByteJunk(t *testing.T) { + var sid SessionID + copy(sid[:], "sniff-junk-sid01") + + // A probe-shaped frame whose payload is not a BHP probe at all. + bogus := frame(ModeProbe, sid, 0, []byte("not-a-probe-payload")) + if got := SniffFrame(bogus); got != VerdictNo { + t.Fatalf("probe with wrong magic = %v, want VerdictNo", got) + } + + // A lane-shaped frame whose payload is not a BLN2 hello. + bogusLane := frame(ModeLane, sid, 0, make([]byte, 12)) + if got := SniffFrame(bogusLane); got != VerdictNo { + t.Fatalf("lane with wrong magic = %v, want VerdictNo", got) + } + + // Unencrypted plaintext magic must also fail: the sniff decrypts with the + // session ID from the same header, so a copied magic string does not pass. + plaintext := make([]byte, HeaderSize+10) + plaintext[0] = ModeProbe + copy(plaintext[1:17], sid[:]) + binary.BigEndian.PutUint32(plaintext[25:29], 10) + copy(plaintext[HeaderSize:], "BHP1") + if got := SniffFrame(plaintext); got != VerdictNo { + t.Fatalf("plaintext magic = %v, want VerdictNo", got) + } + + // A declared payload larger than the protocol allows is not a frame. + oversized := make([]byte, HeaderSize) + oversized[0] = ModeUpload + binary.BigEndian.PutUint32(oversized[25:29], MaxPayload+1) + if got := SniffFrame(oversized); got != VerdictNo { + t.Fatalf("oversized payload = %v, want VerdictNo", got) + } + + // A probe claiming more payload than a probe can hold is not a probe. + longProbe := make([]byte, HeaderSize) + longProbe[0] = ModeProbe + binary.BigEndian.PutUint32(longProbe[25:29], SniffLimit) + if got := SniffFrame(longProbe); got != VerdictNo { + t.Fatalf("over-long probe = %v, want VerdictNo", got) + } +} + +func TestSniffAsksForMoreBytesWhenUndecided(t *testing.T) { + var sid SessionID + copy(sid[:], "sniff-partial-s1") + full := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0)) + + if got := SniffFrame(nil); got != VerdictMore { + t.Fatalf("empty input = %v, want VerdictMore", got) + } + if got := SniffFrame(full[:1]); got != VerdictMore { + t.Fatalf("mode byte only = %v, want VerdictMore", got) + } + if got := SniffFrame(full[:HeaderSize-1]); got != VerdictMore { + t.Fatalf("partial header = %v, want VerdictMore", got) + } + // Header complete but the probe payload still missing. + if got := SniffFrame(full[:HeaderSize]); got != VerdictMore { + t.Fatalf("header without payload = %v, want VerdictMore", got) + } + if got := SniffFrame(full); got != VerdictYes { + t.Fatalf("complete probe = %v, want VerdictYes", got) + } +} diff --git a/internal/bhttp/v2_test.go b/internal/bhttp/v2_test.go new file mode 100644 index 0000000..26de852 --- /dev/null +++ b/internal/bhttp/v2_test.go @@ -0,0 +1,369 @@ +package bhttp + +import ( + "bytes" + "encoding/binary" + "io" + "net" + "testing" + "time" +) + +func v2Request(mode byte, sid SessionID, sequence uint64, clear []byte) Request { + return Request{ + Mode: mode, SID: sid, Seq: sequence, + Payload: Crypt(clear, sid, mode, sequence, false), + } +} + +func TestBHTTPV2CapabilityIsExplicitAndVersioned(t *testing.T) { + var sid SessionID + copy(sid[:], "capability-v2") + clear := make([]byte, 10) + copy(clear[:4], "BHP2") + clear[4] = bhttpV2Version + request := v2Request(ModeProbe, sid, 0, clear) + var response bytes.Buffer + if err := handleProbe(&response, request); err != nil { + t.Fatal(err) + } + status, body, _, err := readTestResponse(&response) + if err != nil || status != StatusOK { + t.Fatalf("status=%d err=%v", status, err) + } + decoded := Crypt(body, sid, ModeProbe, 0, true) + if len(decoded) != 14 || string(decoded[:4]) != "BHP2" || decoded[4] != 2 { + t.Fatalf("invalid capability response %x", decoded) + } + features := binary.BigEndian.Uint32(decoded[6:10]) + if features != bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck { + t.Fatalf("features=%x", features) + } + if maximum := binary.BigEndian.Uint32(decoded[10:14]); maximum != bhttpV2MaxLanes { + t.Fatalf("max lanes=%d", maximum) + } +} + +func TestBHTTPV2LaneResumeAndCommittedUploadACK(t *testing.T) { + targetServer, targetPeer := net.Pipe() + defer targetPeer.Close() + server := NewServer(Config{DialTarget: func(string) (net.Conn, error) { + return targetServer, nil + }}) + defer server.Close() + var sid SessionID + copy(sid[:], "lane-resume-v2!!") + + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneUpload + binary.BigEndian.PutUint32(hello[8:], 7) + request := v2Request(ModeLane, sid, 7, hello) + var first bytes.Buffer + role, firstSession, err := server.attachLane(&first, request) + if err != nil || role != laneUpload { + t.Fatalf("first attach role=%d err=%v", role, err) + } + defer firstSession.ReleaseLane() + _, firstBody, _, err := readTestResponse(&first) + if err != nil { + t.Fatal(err) + } + firstDecoded := Crypt(firstBody, sid, ModeLane, 7, true) + if firstDecoded[5] != 0 { + t.Fatal("first lane unexpectedly resumed") + } + + hello[7] = 1 + request = v2Request(ModeLane, sid, 8, hello) + var resumed bytes.Buffer + _, resumedSession, err := server.attachLane(&resumed, request) + if err != nil { + t.Fatal(err) + } + defer resumedSession.ReleaseLane() + _, resumedBody, _, _ := readTestResponse(&resumed) + resumedDecoded := Crypt(resumedBody, sid, ModeLane, 8, true) + if resumedDecoded[5] != 1 { + t.Fatal("replacement lane did not resume existing SID") + } + + session := server.sessions.GetOrCreate(sid) + var outOfOrder bytes.Buffer + request = v2Request(ModeUpload, sid, 1, []byte("one")) + if err := server.handleRequest(&outOfOrder, session, request, true); err != nil { + t.Fatal(err) + } + _, ackBody, _, _ := readTestResponse(&outOfOrder) + if len(ackBody) != 9 || ackBody[0] != 0 { + t.Fatalf("out-of-order frame was incorrectly committed: %x", ackBody) + } + + targetRead := make(chan []byte, 1) + go func() { + value := make([]byte, len("zeroone")) + _, _ = io.ReadFull(targetPeer, value) + targetRead <- value + }() + var ordered bytes.Buffer + request = v2Request(ModeUpload, sid, 0, []byte("zero")) + if err := server.handleRequest(&ordered, session, request, true); err != nil { + t.Fatal(err) + } + _, ackBody, _, _ = readTestResponse(&ordered) + if len(ackBody) != 9 || ackBody[0] != 1 || binary.BigEndian.Uint64(ackBody[1:]) != 1 { + t.Fatalf("cumulative committed ACK invalid: %x", ackBody) + } + select { + case value := <-targetRead: + if string(value) != "zeroone" { + t.Fatalf("target received %q", value) + } + case <-time.After(time.Second): + t.Fatal("ordered upload did not reach target") + } +} + +func TestBHTTPV2ResumeNeverCreatesExpiredSession(t *testing.T) { + server := NewServer(Config{}) + defer server.Close() + var sid SessionID + copy(sid[:], "expired-resume") + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneDownload + hello[7] = 1 + var response bytes.Buffer + if _, _, err := server.attachLane(&response, v2Request(ModeLane, sid, 1, hello)); err == nil { + t.Fatal("expired resume was accepted") + } + if _, exists := server.sessions.Get(sid); exists { + t.Fatal("resume rejection silently created a new session") + } +} + +func TestBHTTPV2PersistentLaneCarriesMultipleRequests(t *testing.T) { + targetServer, targetPeer := net.Pipe() + defer targetPeer.Close() + server := NewServer(Config{DialTarget: func(string) (net.Conn, error) { + return targetServer, nil + }}) + defer server.Close() + accepted, client := net.Pipe() + done := make(chan error, 1) + go func() { done <- server.handleConnection(accepted) }() + defer func() { + _ = client.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("persistent handler did not stop") + } + }() + _ = client.SetDeadline(time.Now().Add(2 * time.Second)) + var sid SessionID + copy(sid[:], "persistent-v2") + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneUpload + binary.BigEndian.PutUint32(hello[8:], 11) + request := v2Request(ModeLane, sid, 11, hello) + if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil { + t.Fatal(err) + } + status, _, _, err := readTestResponse(client) + if err != nil || status != StatusOK { + t.Fatalf("lane attach status=%d err=%v", status, err) + } + + want := []byte("firstsecond") + received := make(chan []byte, 1) + go func() { + value := make([]byte, len(want)) + _, _ = io.ReadFull(targetPeer, value) + received <- value + }() + for sequence, clear := range [][]byte{[]byte("first"), []byte("second")} { + request = v2Request(ModeUpload, sid, uint64(sequence), clear) + if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil { + t.Fatal(err) + } + status, body, _, readErr := readTestResponse(client) + if readErr != nil || status != StatusOK || len(body) != 9 || body[0] != 1 { + t.Fatalf("upload %d status=%d body=%x err=%v", sequence, status, body, readErr) + } + if committed := binary.BigEndian.Uint64(body[1:]); committed != uint64(sequence) { + t.Fatalf("upload %d committed=%d", sequence, committed) + } + } + select { + case got := <-received: + if !bytes.Equal(got, want) { + t.Fatalf("persistent lane target=%q", got) + } + case <-time.After(time.Second): + t.Fatal("persistent lane did not forward both requests") + } +} + +func TestBHTTPV2ReplayAfterLaneReplacementDoesNotDuplicateBytes(t *testing.T) { + targetServer, targetPeer := net.Pipe() + defer targetPeer.Close() + server := NewServer(Config{DialTarget: func(string) (net.Conn, error) { + return targetServer, nil + }}) + defer server.Close() + var sid SessionID + copy(sid[:], "replay-lane-v2") + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneUpload + firstRequest := v2Request(ModeLane, sid, 1, hello) + var first bytes.Buffer + _, firstSession, err := server.attachLane(&first, firstRequest) + if err != nil { + t.Fatal(err) + } + firstSession.ReleaseLane() + + want := []byte("firstsecond") + received := make(chan []byte, 1) + go func() { + value := make([]byte, len(want)) + _, _ = io.ReadFull(targetPeer, value) + received <- value + }() + session := server.sessions.GetOrCreate(sid) + var response bytes.Buffer + if err := server.handleRequest(&response, session, + v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil { + t.Fatal(err) + } + + hello[7] = 1 + var replacement bytes.Buffer + _, replacementSession, err := server.attachLane(&replacement, + v2Request(ModeLane, sid, 2, hello)) + if err != nil { + t.Fatal(err) + } + defer replacementSession.ReleaseLane() + response.Reset() + if err := server.handleRequest(&response, session, + v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil { + t.Fatal(err) + } + response.Reset() + if err := server.handleRequest(&response, session, + v2Request(ModeUpload, sid, 1, []byte("second")), true); err != nil { + t.Fatal(err) + } + select { + case got := <-received: + if !bytes.Equal(got, want) { + t.Fatalf("replayed target bytes=%q", got) + } + case <-time.After(time.Second): + t.Fatal("replacement lane did not finish upload") + } +} + +func TestBHTTPV2LaneLimitIsEnforced(t *testing.T) { + targetServer, targetPeer := net.Pipe() + defer targetPeer.Close() + server := NewServer(Config{MaxV2Lanes: 1, DialTarget: func(string) (net.Conn, error) { + return targetServer, nil + }}) + defer server.Close() + var sid SessionID + copy(sid[:], "lane-limit-v2") + hello := make([]byte, 12) + copy(hello[:4], "BLN2") + hello[4] = 2 + hello[5] = laneUpload + var first bytes.Buffer + _, session, err := server.attachLane(&first, v2Request(ModeLane, sid, 1, hello)) + if err != nil { + t.Fatal(err) + } + defer session.ReleaseLane() + hello[5] = laneDownload + hello[7] = 1 + binary.BigEndian.PutUint32(hello[8:], 2) + var rejected bytes.Buffer + if _, _, err := server.attachLane(&rejected, + v2Request(ModeLane, sid, 2, hello)); err == nil { + t.Fatal("second lane exceeded configured limit") + } +} + +func TestBHTTPV2LaneReplacementKeepsSingleLogicalSlot(t *testing.T) { + session := NewSession(SessionID{}) + first, ok := session.AcquireLane(7, 1) + if !ok { + t.Fatal("first logical lane was rejected") + } + replacement, ok := session.AcquireLane(7, 1) + if !ok { + t.Fatal("replacement of the same lane ID consumed another slot") + } + first.ReleaseLane() + if _, ok := session.AcquireLane(8, 1); ok { + t.Fatal("stale release removed the replacement generation") + } + replacement.ReleaseLane() + if final, ok := session.AcquireLane(8, 1); !ok { + t.Fatal("released replacement did not free its logical slot") + } else { + final.ReleaseLane() + } +} + +func TestServerCloseAbortsIdlePersistentConnections(t *testing.T) { + server := NewServer(Config{}) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + serveDone := make(chan error, 1) + go func() { serveDone <- server.Serve(listener) }() + connection, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + deadline := time.Now().Add(time.Second) + for { + server.connMu.Lock() + active := len(server.active) + server.connMu.Unlock() + if active == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("server did not track idle connection") + } + time.Sleep(time.Millisecond) + } + _ = listener.Close() + server.Close() + waitDone := make(chan struct{}) + go func() { + server.Wait() + close(waitDone) + }() + select { + case <-waitDone: + case <-time.After(time.Second): + t.Fatal("server shutdown waited on idle persistent connection") + } + select { + case <-serveDone: + case <-time.After(time.Second): + t.Fatal("Serve did not return after listener close") + } +} diff --git a/internal/btun/auth.go b/internal/btun/auth.go new file mode 100644 index 0000000..0dca272 --- /dev/null +++ b/internal/btun/auth.go @@ -0,0 +1,62 @@ +package btun + +import ( + "context" + "io" +) + +// Authenticator verifies a BTUN credential. The panel supplies its own +// implementation backed by the same account database the built-in SSH server +// uses, so a BTUN login is exactly as strong as an SSH login on this server. +// +// This package deliberately ships no PAM, /etc/shadow or password-file +// backend: BTUN accounts are panel accounts and nothing else. +type Authenticator interface { + Authenticate(username, password string) error + Name() string +} + +// AllowAuthenticator accepts every credential. It exists only for the package +// tests, which exercise the wire protocol rather than the account database. It +// is never selectable from the panel configuration. +type AllowAuthenticator struct{} + +func (AllowAuthenticator) Authenticate(_, _ string) error { return nil } +func (AllowAuthenticator) Name() string { return "allow-insecure" } + +// Accountant lets the embedding application admit a freshly authenticated +// session and then meter its traffic. It is optional: when Config.Accountant +// is nil, sessions are admitted unconditionally and no metering happens. +type Accountant interface { + // Admit is called once per session, immediately after the credential was + // accepted. Returning an error refuses the session, which is how + // per-account connection limits are enforced. The returned Ledger is + // closed exactly once when the session ends. + // + // closer ends this session on demand, so the application can force a + // disconnect (an account being deleted, edited, or hit by a panel-wide + // restart) without waiting for the next packet to be metered. + Admit(username, remote string, closer io.Closer) (Ledger, error) +} + +// Ledger meters one BTUN session. Uplink and Downlink are called before the +// corresponding packet is forwarded, so returning an error drops the session +// instead of letting it exceed its allowance. Implementations must be safe for +// concurrent use: Uplink runs on the session's reader goroutine while Downlink +// runs on the shared TUN reader goroutine. +type Ledger interface { + // Uplink accounts for n bytes travelling client -> internet. It may block + // while rate limiting and returns an error when the session must end. + Uplink(ctx context.Context, n int) error + // Downlink accounts for n bytes travelling internet -> client. + Downlink(ctx context.Context, n int) error + // Close releases whatever the ledger reserved for this session. + Close() +} + +// nopLedger is used when no Accountant is configured. +type nopLedger struct{} + +func (nopLedger) Uplink(context.Context, int) error { return nil } +func (nopLedger) Downlink(context.Context, int) error { return nil } +func (nopLedger) Close() {} diff --git a/internal/btun/pool.go b/internal/btun/pool.go new file mode 100644 index 0000000..f9eba10 --- /dev/null +++ b/internal/btun/pool.go @@ -0,0 +1,73 @@ +package btun + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "sync" +) + +type AddressPool struct { + mu sync.Mutex + network uint32 + first uint32 + last uint32 + next uint32 + used map[uint32]struct{} +} + +func NewAddressPool(cidr string) (*AddressPool, error) { + ip, network, err := net.ParseCIDR(cidr) + if err != nil { + return nil, fmt.Errorf("parse subnet: %w", err) + } + v4 := ip.To4() + if v4 == nil { + return nil, errors.New("BTUN subnet must be IPv4") + } + ones, bits := network.Mask.Size() + if bits != 32 || ones > 30 { + return nil, errors.New("BTUN subnet must contain at least four IPv4 addresses") + } + base := binary.BigEndian.Uint32(v4) & binary.BigEndian.Uint32(network.Mask) + size := uint64(1) << uint(32-ones) + last := uint32(uint64(base) + size - 2) + first := base + 2 + if first > last { + return nil, errors.New("BTUN subnet has no client addresses") + } + return &AddressPool{network: base, first: first, last: last, next: first, used: make(map[uint32]struct{})}, nil +} + +func (pool *AddressPool) Acquire() (net.IP, error) { + pool.mu.Lock() + defer pool.mu.Unlock() + capacity := uint64(pool.last) - uint64(pool.first) + 1 + for checked := uint64(0); checked < capacity; checked++ { + candidate := pool.next + pool.next++ + if pool.next > pool.last { + pool.next = pool.first + } + if _, exists := pool.used[candidate]; exists { + continue + } + pool.used[candidate] = struct{}{} + var raw [4]byte + binary.BigEndian.PutUint32(raw[:], candidate) + return net.IPv4(raw[0], raw[1], raw[2], raw[3]), nil + } + return nil, errors.New("BTUN address pool exhausted") +} + +func (pool *AddressPool) Release(ip net.IP) { + v4 := ip.To4() + if v4 == nil { + return + } + value := binary.BigEndian.Uint32(v4) + pool.mu.Lock() + delete(pool.used, value) + pool.mu.Unlock() +} diff --git a/internal/btun/protocol.go b/internal/btun/protocol.go new file mode 100644 index 0000000..dc9e71a --- /dev/null +++ b/internal/btun/protocol.go @@ -0,0 +1,161 @@ +package btun + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "net" +) + +const ( + PacketAuth byte = 1 + PacketAuthResponse byte = 2 + PacketIP byte = 3 + PacketData byte = 4 + PacketKeepAlive byte = 5 + + HeaderSize = 6 + DefaultMaxPacket = 64 * 1024 +) + +var ( + ClientHello = []byte("DTUNNEL/1.1 CLIENT_HELLO\r\n") + ServerHello = []byte("DTUNNEL/1.1 SERVER_HELLO\r\n") +) + +type Packet struct { + Type byte + Flags byte + Payload []byte +} + +func MarshalPacket(packet Packet, maxPayload int) ([]byte, error) { + if maxPayload <= 0 { + maxPayload = DefaultMaxPacket + } + if len(packet.Payload) > maxPayload { + return nil, fmt.Errorf("packet payload too large: %d", len(packet.Payload)) + } + encoded := make([]byte, HeaderSize+len(packet.Payload)) + encoded[0] = packet.Type + encoded[1] = packet.Flags + binary.BigEndian.PutUint32(encoded[2:6], uint32(len(packet.Payload))) + copy(encoded[HeaderSize:], packet.Payload) + return encoded, nil +} + +func ReadPacket(reader io.Reader, maxPayload int) (Packet, error) { + if maxPayload <= 0 { + maxPayload = DefaultMaxPacket + } + var header [HeaderSize]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return Packet{}, err + } + length := int(binary.BigEndian.Uint32(header[2:6])) + if length > maxPayload { + return Packet{}, fmt.Errorf("packet payload too large: %d", length) + } + payload := make([]byte, length) + if _, err := io.ReadFull(reader, payload); err != nil { + return Packet{}, err + } + return Packet{Type: header[0], Flags: header[1], Payload: payload}, nil +} + +func ParseDatagram(datagram []byte, maxPayload int) (Packet, error) { + if len(datagram) < HeaderSize { + return Packet{}, errors.New("datagram is shorter than the packet header") + } + if maxPayload <= 0 { + maxPayload = DefaultMaxPacket + } + length := int(binary.BigEndian.Uint32(datagram[2:6])) + if length > maxPayload { + return Packet{}, fmt.Errorf("packet payload too large: %d", length) + } + if len(datagram) != HeaderSize+length { + return Packet{}, fmt.Errorf("invalid datagram length: got %d, want %d", len(datagram), HeaderSize+length) + } + payload := append([]byte(nil), datagram[HeaderSize:]...) + return Packet{Type: datagram[0], Flags: datagram[1], Payload: payload}, nil +} + +func ReadClientHello(reader io.Reader, maxCoverBytes int) (int, error) { + if maxCoverBytes < 0 { + maxCoverBytes = 0 + } + readLimit := maxCoverBytes + len(ClientHello) + window := make([]byte, 0, len(ClientHello)) + var one [1]byte + for consumed := 0; consumed < readLimit; consumed++ { + if _, err := io.ReadFull(reader, one[:]); err != nil { + return consumed, err + } + if len(window) == cap(window) { + copy(window, window[1:]) + window = window[:len(window)-1] + } + window = append(window, one[0]) + if bytes.Equal(window, ClientHello) { + return consumed + 1 - len(ClientHello), nil + } + } + return maxCoverBytes, errors.New("client hello not found") +} + +func ParseCredential(payload []byte) (string, string, error) { + separator := bytes.IndexByte(payload, ':') + if separator <= 0 { + return "", "", errors.New("invalid credential") + } + username := string(payload[:separator]) + password := string(payload[separator+1:]) + if len(username) > 256 || len(password) > 4096 || bytes.IndexByte(payload, 0) >= 0 { + return "", "", errors.New("invalid credential") + } + return username, password, nil +} + +func AuthResponse(accepted bool, message string) Packet { + payload := make([]byte, 1, 1+len(message)) + if accepted { + payload[0] = 1 + } + payload = append(payload, message...) + return Packet{Type: PacketAuthResponse, Payload: payload} +} + +func ParseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, ok bool) { + source, destination, _, ok = parseIPv4Packet(packet) + return source, destination, ok +} + +func parseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, totalLength int, ok bool) { + if len(packet) < 20 || packet[0]>>4 != 4 { + return source, destination, 0, false + } + headerLength := int(packet[0]&0x0f) * 4 + if headerLength < 20 || headerLength > len(packet) { + return source, destination, 0, false + } + totalLength = int(binary.BigEndian.Uint16(packet[2:4])) + if totalLength < headerLength || totalLength > len(packet) { + return source, destination, 0, false + } + copy(source[:], packet[12:16]) + copy(destination[:], packet[16:20]) + return source, destination, totalLength, true +} + +func ipKey(ip net.IP) ([4]byte, bool) { + var key [4]byte + v4 := ip.To4() + if v4 == nil { + return key, false + } + copy(key[:], v4) + return key, true +} diff --git a/internal/btun/protocol_test.go b/internal/btun/protocol_test.go new file mode 100644 index 0000000..cd34717 --- /dev/null +++ b/internal/btun/protocol_test.go @@ -0,0 +1,68 @@ +package btun + +import ( + "bytes" + "encoding/binary" + "net" + "testing" +) + +func TestPacketRoundTrip(t *testing.T) { + want := Packet{Type: PacketData, Payload: []byte{1, 2, 3, 4}} + encoded, err := MarshalPacket(want, 1024) + if err != nil { + t.Fatal(err) + } + got, err := ReadPacket(bytes.NewReader(encoded), 1024) + if err != nil { + t.Fatal(err) + } + if got.Type != want.Type || got.Flags != want.Flags || !bytes.Equal(got.Payload, want.Payload) { + t.Fatalf("packet mismatch: %#v != %#v", got, want) + } +} + +func TestReadClientHelloAfterCoverBytes(t *testing.T) { + cover := []byte("GET / HTTP/1.1\r\nHost: example.test\r\n\r\n") + stream := append(append([]byte(nil), cover...), ClientHello...) + consumed, err := ReadClientHello(bytes.NewReader(stream), len(cover)) + if err != nil { + t.Fatal(err) + } + if consumed != len(cover) { + t.Fatalf("cover bytes = %d, want %d", consumed, len(cover)) + } +} + +func TestAddressPool(t *testing.T) { + pool, err := NewAddressPool("10.77.0.0/29") + if err != nil { + t.Fatal(err) + } + first, err := pool.Acquire() + if err != nil { + t.Fatal(err) + } + if !first.Equal(net.IPv4(10, 77, 0, 2)) { + t.Fatalf("first address = %s", first) + } + pool.Release(first) +} + +func TestIPv4ParserAcceptsTransportPadding(t *testing.T) { + packet := make([]byte, 28) + packet[0] = 0x45 + binary.BigEndian.PutUint16(packet[2:4], 20) + copy(packet[12:16], []byte{10, 77, 0, 2}) + copy(packet[16:20], []byte{1, 1, 1, 1}) + source, destination, totalLength, ok := parseIPv4Packet(packet) + if !ok { + t.Fatal("padded IPv4 packet was rejected") + } + if source != [4]byte{10, 77, 0, 2} || destination != [4]byte{1, 1, 1, 1} { + t.Fatalf("unexpected addresses: %v -> %v", source, destination) + } + if totalLength != 20 { + t.Fatalf("IPv4 length = %d, want 20", totalLength) + } +} diff --git a/internal/btun/server.go b/internal/btun/server.go new file mode 100644 index 0000000..0efe197 --- /dev/null +++ b/internal/btun/server.go @@ -0,0 +1,798 @@ +package btun + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "strings" + "sync" + "sync/atomic" + "time" +) + +type PacketDevice interface { + io.ReadWriteCloser + Name() string +} + +type Config struct { + Subnet string + Authenticator Authenticator + // Accountant is an optional hook the embedding application uses to admit + // authenticated sessions and meter their traffic. Nil admits every session + // and meters nothing. + Accountant Accountant + Logger *log.Logger + HandshakeTimeout time.Duration + IdleTimeout time.Duration + MaxPacketSize int + MaxCoverBytes int + // MaxSessions caps concurrently tracked sessions across both transports. + // Zero or negative disables the cap. + MaxSessions int + // LogConnections enables one log line per session start/stop. Leave it off + // on busy servers. + LogConnections bool +} + +type StatsSnapshot struct { + StartedAt time.Time `json:"startedAt"` + ActiveSessions uint64 `json:"activeSessions"` + Accepted uint64 `json:"accepted"` + AuthSucceeded uint64 `json:"authSucceeded"` + AuthRejected uint64 `json:"authRejected"` + ClientPackets uint64 `json:"clientPackets"` + InternetPackets uint64 `json:"internetPackets"` + ClientBytes uint64 `json:"clientBytes"` + InternetBytes uint64 `json:"internetBytes"` + DroppedPackets uint64 `json:"droppedPackets"` + SessionsRejected uint64 `json:"sessionsRejected"` +} + +type counters struct { + activeSessions atomic.Uint64 + accepted atomic.Uint64 + authSucceeded atomic.Uint64 + authRejected atomic.Uint64 + clientPackets atomic.Uint64 + internetPackets atomic.Uint64 + clientBytes atomic.Uint64 + internetBytes atomic.Uint64 + droppedPackets atomic.Uint64 + sessionsRejected atomic.Uint64 +} + +type Server struct { + config Config + tun PacketDevice + pool *AddressPool + started time.Time + stats counters + + mu sync.RWMutex + sessions map[*session]struct{} + byIP map[[4]byte]*session + udpByAddr map[string]*session + closers []io.Closer + + tunWriteMu sync.Mutex + closed chan struct{} + closeOnce sync.Once + wait sync.WaitGroup +} + +type session struct { + server *Server + transport sessionTransport + udpKey string + user string + ledger Ledger + ctx context.Context + cancel context.CancelFunc + + mu sync.Mutex + authenticated bool + assignedIP net.IP + lastActive time.Time + handleMu sync.Mutex + closeOnce sync.Once + invalidFrames uint64 +} + +type sessionTransport interface { + Send(Packet, int) (int, error) + Close() error + Remote() string +} + +type tcpTransport struct { + connection net.Conn + writeMu sync.Mutex +} + +func (transport *tcpTransport) Send(packet Packet, maxPayload int) (int, error) { + encoded, err := MarshalPacket(packet, maxPayload) + if err != nil { + return 0, err + } + transport.writeMu.Lock() + defer transport.writeMu.Unlock() + return len(encoded), writeFull(transport.connection, encoded) +} + +func (transport *tcpTransport) Close() error { return transport.connection.Close() } +func (transport *tcpTransport) Remote() string { return transport.connection.RemoteAddr().String() } + +type udpTransport struct { + connection net.PacketConn + address net.Addr + writeMu sync.Mutex +} + +func (transport *udpTransport) Send(packet Packet, maxPayload int) (int, error) { + encoded, err := MarshalPacket(packet, maxPayload) + if err != nil { + return 0, err + } + transport.writeMu.Lock() + defer transport.writeMu.Unlock() + written, err := transport.connection.WriteTo(encoded, transport.address) + if err == nil && written != len(encoded) { + err = io.ErrShortWrite + } + return written, err +} + +func (transport *udpTransport) Close() error { return nil } +func (transport *udpTransport) Remote() string { return transport.address.String() } + +func NewServer(config Config, tun PacketDevice) (*Server, error) { + if tun == nil { + return nil, errors.New("TUN device is required") + } + if config.Authenticator == nil { + return nil, errors.New("authenticator is required") + } + if config.Subnet == "" { + config.Subnet = "10.77.0.0/16" + } + if config.Logger == nil { + config.Logger = log.Default() + } + if config.HandshakeTimeout <= 0 { + config.HandshakeTimeout = 15 * time.Second + } + if config.IdleTimeout <= 0 { + config.IdleTimeout = 2 * time.Minute + } + if config.MaxPacketSize <= 0 { + config.MaxPacketSize = DefaultMaxPacket + } + if config.MaxPacketSize > 4*1024*1024 { + return nil, errors.New("maximum packet size cannot exceed 4 MiB") + } + if config.MaxCoverBytes <= 0 { + config.MaxCoverBytes = 64 * 1024 + } + pool, err := NewAddressPool(config.Subnet) + if err != nil { + return nil, err + } + server := &Server{ + config: config, tun: tun, pool: pool, started: time.Now(), + sessions: make(map[*session]struct{}), byIP: make(map[[4]byte]*session), + udpByAddr: make(map[string]*session), closed: make(chan struct{}), + } + server.wait.Add(2) + go server.tunLoop() + go server.cleanupLoop() + return server, nil +} + +func (server *Server) ServeTCP(listener net.Listener) error { + server.addCloser(listener) + server.config.Logger.Printf("BTUN TCP listening on %s", listener.Addr()) + for { + connection, err := listener.Accept() + if err != nil { + if server.isClosed() || errors.Is(err, net.ErrClosed) { + return nil + } + return err + } + server.stats.accepted.Add(1) + if tcp, ok := connection.(*net.TCPConn); ok { + _ = tcp.SetNoDelay(true) + _ = tcp.SetKeepAlive(true) + _ = tcp.SetKeepAlivePeriod(30 * time.Second) + } + server.wait.Add(1) + go func() { + defer server.wait.Done() + server.runTCP(connection) + }() + } +} + +// ServeConn serves one already-accepted TCP connection, for listeners this +// server does not own. A port shared with SSH or HTTP routes a client here once +// its hello has been identified; the session is then authenticated, counted and +// closed exactly like one from ServeTCP's own accept loop. +// +// It blocks until the session ends, and reports whether the server was still +// running when the connection arrived. A refused connection is closed here, and +// the caller must not keep using the connection either way. +func (server *Server) ServeConn(connection net.Conn) bool { + if server.isClosed() { + _ = connection.Close() + return false + } + server.stats.accepted.Add(1) + server.wait.Add(1) + defer server.wait.Done() + server.runTCP(connection) + return true +} + +// runTCP drives one TCP connection to completion. +func (server *Server) runTCP(connection net.Conn) { + if err := server.handleTCP(connection); err != nil && !normalClose(err) { + server.config.Logger.Printf("BTUN TCP %s: %v", connection.RemoteAddr(), err) + } +} + +func (server *Server) handleTCP(connection net.Conn) error { + transport := &tcpTransport{connection: connection} + current := server.newSession(transport, "") + if current == nil { + return errors.New("BTUN session limit reached") + } + defer current.close() + _ = connection.SetDeadline(time.Now().Add(server.config.HandshakeTimeout)) + coverBytes, err := ReadClientHello(connection, server.config.MaxCoverBytes) + if err != nil { + return fmt.Errorf("handshake: %w", err) + } + if coverBytes > 0 { + server.config.Logger.Printf("BTUN TCP %s accepted %d cover bytes", transport.Remote(), coverBytes) + } + if err := writeFull(connection, ServerHello); err != nil { + return fmt.Errorf("write server hello: %w", err) + } + authPacket, err := ReadPacket(connection, server.config.MaxPacketSize) + if err != nil { + return fmt.Errorf("read authentication: %w", err) + } + if err := server.authenticate(current, authPacket); err != nil { + return err + } + _ = connection.SetDeadline(time.Time{}) + for { + if server.config.IdleTimeout > 0 { + _ = connection.SetReadDeadline(time.Now().Add(server.config.IdleTimeout)) + } + packet, err := ReadPacket(connection, server.config.MaxPacketSize) + if err != nil { + return err + } + if err := server.handleClientPacket(current, packet); err != nil { + return err + } + } +} + +func (server *Server) ServeUDP(connection net.PacketConn) error { + server.addCloser(connection) + server.config.Logger.Printf("BTUN UDP listening on %s", connection.LocalAddr()) + buffer := make([]byte, server.config.MaxPacketSize+HeaderSize) + for { + length, address, err := connection.ReadFrom(buffer) + if err != nil { + if server.isClosed() || errors.Is(err, net.ErrClosed) { + return nil + } + return err + } + datagram := append([]byte(nil), buffer[:length]...) + if bytes.Equal(datagram, ClientHello) { + server.startUDPSession(connection, address) + continue + } + server.mu.RLock() + current := server.udpByAddr[address.String()] + server.mu.RUnlock() + if current == nil { + server.stats.droppedPackets.Add(1) + continue + } + packet, err := ParseDatagram(datagram, server.config.MaxPacketSize) + if err != nil { + server.stats.droppedPackets.Add(1) + continue + } + current.handleMu.Lock() + if !current.isAuthenticated() { + err = server.authenticate(current, packet) + } else { + err = server.handleClientPacket(current, packet) + } + current.handleMu.Unlock() + if err != nil { + server.config.Logger.Printf("BTUN UDP %s: %v", address, err) + current.close() + } + } +} + +func (server *Server) startUDPSession(connection net.PacketConn, address net.Addr) { + server.stats.accepted.Add(1) + key := address.String() + transport := &udpTransport{connection: connection, address: address} + current := server.newSession(transport, key) + if current == nil { + return + } + server.mu.Lock() + previous := server.udpByAddr[key] + server.udpByAddr[key] = current + server.mu.Unlock() + if previous != nil && previous != current { + previous.close() + } + if _, err := connection.WriteTo(ServerHello, address); err != nil { + current.close() + return + } + server.config.Logger.Printf("BTUN UDP handshake from %s", address) +} + +func (server *Server) authenticate(current *session, packet Packet) error { + if packet.Type != PacketAuth || packet.Flags != 0 { + server.stats.authRejected.Add(1) + _ = current.send(AuthResponse(false, "authentication required")) + return errors.New("authentication packet required") + } + username, password, err := ParseCredential(packet.Payload) + if err != nil { + server.stats.authRejected.Add(1) + _ = current.send(AuthResponse(false, "invalid credential")) + return err + } + if err := server.config.Authenticator.Authenticate(username, password); err != nil { + server.stats.authRejected.Add(1) + _ = current.send(AuthResponse(false, "invalid username or password")) + return errors.New("authentication rejected") + } + // Admission comes after the credential check so per-account connection + // limits and data quotas are enforced by the same code path the built-in + // SSH server uses. A refusal here is a policy decision, not a bad password, + // and is reported to the client as such. + if server.config.Accountant != nil { + ledger, err := server.config.Accountant.Admit(username, current.transport.Remote(), sessionCloser{session: current}) + if err != nil { + server.stats.authRejected.Add(1) + _ = current.send(AuthResponse(false, err.Error())) + return fmt.Errorf("session refused for %s: %w", username, err) + } + if ledger == nil { + ledger = nopLedger{} + } + current.mu.Lock() + current.ledger = ledger + current.mu.Unlock() + } + current.mu.Lock() + current.authenticated = true + current.user = username + current.lastActive = time.Now() + current.mu.Unlock() + server.stats.authSucceeded.Add(1) + if err := current.send(AuthResponse(true, "authenticated")); err != nil { + return fmt.Errorf("write authentication response: %w", err) + } + if server.config.LogConnections { + server.config.Logger.Printf("BTUN %s authenticated user=%s via %s", current.transport.Remote(), username, server.config.Authenticator.Name()) + } + return nil +} + +func (server *Server) handleClientPacket(current *session, packet Packet) error { + current.touch() + if packet.Flags != 0 { + return errors.New("unsupported packet flags") + } + switch packet.Type { + case PacketIP: + if len(packet.Payload) != 0 { + return errors.New("invalid IP request") + } + ip, err := server.assignIP(current) + if err != nil { + return err + } + return current.send(Packet{Type: PacketIP, Payload: append([]byte(nil), ip.To4()...)}) + case PacketData: + source, _, totalLength, ok := parseIPv4Packet(packet.Payload) + assigned, assignedOK := current.ipKey() + if !ok { + server.stats.droppedPackets.Add(1) + server.logDroppedFrame(current, "invalid IPv4", packet.Payload, assigned, assignedOK) + return nil + } + if !assignedOK || source != assigned { + server.stats.droppedPackets.Add(1) + server.logDroppedFrame(current, "source mismatch", packet.Payload, assigned, assignedOK) + return nil + } + payload := packet.Payload[:totalLength] + if err := current.meter(true, len(payload)); err != nil { + return err + } + server.tunWriteMu.Lock() + written, err := server.tun.Write(payload) + server.tunWriteMu.Unlock() + if err != nil { + return fmt.Errorf("write TUN: %w", err) + } + if written != len(payload) { + return io.ErrShortWrite + } + server.stats.clientPackets.Add(1) + server.stats.clientBytes.Add(uint64(written)) + return nil + case PacketKeepAlive: + if len(packet.Payload) != 0 { + return errors.New("invalid keep-alive packet") + } + return nil + default: + return fmt.Errorf("unknown packet type %d", packet.Type) + } +} + +func (server *Server) logDroppedFrame(current *session, reason string, payload []byte, + assigned [4]byte, assignedOK bool) { + current.mu.Lock() + current.invalidFrames++ + count := current.invalidFrames + current.mu.Unlock() + if count > 3 { + return + } + version := byte(0) + declared := 0 + if len(payload) > 0 { + version = payload[0] >> 4 + } + if len(payload) >= 4 { + declared = int(binary.BigEndian.Uint16(payload[2:4])) + } + source := "n/a" + if len(payload) >= 16 { + source = net.IP(payload[12:16]).String() + } + assignedText := "none" + if assignedOK { + assignedText = net.IP(assigned[:]).String() + } + server.config.Logger.Printf( + "BTUN %s dropped data frame (%s): frameLen=%d ipVersion=%d ipLen=%d source=%s assigned=%s", + current.transport.Remote(), reason, len(payload), version, declared, source, assignedText) +} + +func (server *Server) assignIP(current *session) (net.IP, error) { + current.mu.Lock() + if current.assignedIP != nil { + ip := append(net.IP(nil), current.assignedIP...) + current.mu.Unlock() + return ip, nil + } + current.mu.Unlock() + ip, err := server.pool.Acquire() + if err != nil { + return nil, err + } + key, _ := ipKey(ip) + server.mu.Lock() + if existing := server.byIP[key]; existing != nil && existing != current { + server.mu.Unlock() + server.pool.Release(ip) + return nil, errors.New("address collision") + } + current.mu.Lock() + if current.assignedIP == nil { + current.assignedIP = append(net.IP(nil), ip.To4()...) + server.byIP[key] = current + } else { + server.pool.Release(ip) + ip = append(net.IP(nil), current.assignedIP...) + } + current.mu.Unlock() + server.mu.Unlock() + server.config.Logger.Printf("BTUN %s assigned %s", current.transport.Remote(), ip) + return ip, nil +} + +func (server *Server) tunLoop() { + defer server.wait.Done() + buffer := make([]byte, server.config.MaxPacketSize) + for { + length, err := server.tun.Read(buffer) + if err != nil { + if !server.isClosed() && !errors.Is(err, net.ErrClosed) && !errors.Is(err, io.EOF) { + server.config.Logger.Printf("BTUN TUN read stopped: %v", err) + } + return + } + packet := append([]byte(nil), buffer[:length]...) + _, destination, ok := ParseIPv4Packet(packet) + if !ok { + server.stats.droppedPackets.Add(1) + continue + } + server.mu.RLock() + current := server.byIP[destination] + server.mu.RUnlock() + if current == nil { + server.stats.droppedPackets.Add(1) + continue + } + if err := current.meter(false, length); err != nil { + current.close() + continue + } + if err := current.send(Packet{Type: PacketData, Payload: packet}); err != nil { + current.close() + continue + } + server.stats.internetPackets.Add(1) + server.stats.internetBytes.Add(uint64(length)) + } +} + +func (server *Server) cleanupLoop() { + defer server.wait.Done() + interval := server.config.IdleTimeout / 2 + if interval < time.Second { + interval = time.Second + } + if interval > 30*time.Second { + interval = 30 * time.Second + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + server.mu.RLock() + candidates := make([]*session, 0, len(server.sessions)) + for current := range server.sessions { + candidates = append(candidates, current) + } + server.mu.RUnlock() + for _, current := range candidates { + if now.Sub(current.lastSeen()) > server.config.IdleTimeout { + current.close() + } + } + case <-server.closed: + return + } + } +} + +func (server *Server) newSession(transport sessionTransport, udpKey string) *session { + ctx, cancel := context.WithCancel(context.Background()) + current := &session{ + server: server, transport: transport, udpKey: udpKey, + lastActive: time.Now(), ledger: nopLedger{}, ctx: ctx, cancel: cancel, + } + server.mu.Lock() + if maximum := server.config.MaxSessions; maximum > 0 && len(server.sessions) >= maximum { + server.mu.Unlock() + cancel() + server.stats.sessionsRejected.Add(1) + rejected := server.stats.sessionsRejected.Load() + if rejected == 1 || rejected%1000 == 0 { + server.config.Logger.Printf("BTUN session cap reached (%d); rejected %d session(s) so far", + maximum, rejected) + } + _ = transport.Close() + return nil + } + server.sessions[current] = struct{}{} + server.mu.Unlock() + server.stats.activeSessions.Add(1) + return current +} + +func (current *session) send(packet Packet) error { + written, err := current.transport.Send(packet, current.server.config.MaxPacketSize) + if err == nil { + current.touch() + _ = written + } + return err +} + +func (current *session) touch() { + current.mu.Lock() + current.lastActive = time.Now() + current.mu.Unlock() +} + +func (current *session) lastSeen() time.Time { + current.mu.Lock() + defer current.mu.Unlock() + return current.lastActive +} + +func (current *session) isAuthenticated() bool { + current.mu.Lock() + defer current.mu.Unlock() + return current.authenticated +} + +func (current *session) ipKey() ([4]byte, bool) { + current.mu.Lock() + defer current.mu.Unlock() + return ipKey(current.assignedIP) +} + +func (current *session) close() { + current.closeOnce.Do(func() { + if current.cancel != nil { + current.cancel() + } + // The ledger is installed by authenticate under this lock, so it has to + // be read under it too. + current.mu.Lock() + ledger := current.ledger + current.ledger = nil + current.mu.Unlock() + if ledger != nil { + ledger.Close() + } + _ = current.transport.Close() + server := current.server + server.mu.Lock() + delete(server.sessions, current) + if current.udpKey != "" && server.udpByAddr[current.udpKey] == current { + delete(server.udpByAddr, current.udpKey) + } + current.mu.Lock() + assigned := append(net.IP(nil), current.assignedIP...) + current.assignedIP = nil + current.mu.Unlock() + if key, ok := ipKey(assigned); ok && server.byIP[key] == current { + delete(server.byIP, key) + } + server.mu.Unlock() + if assigned != nil { + server.pool.Release(assigned) + } + server.stats.activeSessions.Add(^uint64(0)) + if server.config.LogConnections { + server.config.Logger.Printf("BTUN session end: remote=%s user=%s", current.transport.Remote(), current.username()) + } + }) +} + +// sessionCloser lets an Accountant end a session it previously admitted. +type sessionCloser struct{ session *session } + +func (c sessionCloser) Close() error { + c.session.close() + return nil +} + +// meter runs the session's ledger for n forwarded bytes. Uplink is +// client -> internet; downlink is internet -> client. An error means the +// account ran out of allowance (or was closed) and the session must end. +func (current *session) meter(uplink bool, n int) error { + if n <= 0 { + return nil + } + current.mu.Lock() + ledger := current.ledger + current.mu.Unlock() + if ledger == nil { + return nil + } + if uplink { + return ledger.Uplink(current.ctx, n) + } + return ledger.Downlink(current.ctx, n) +} + +func (current *session) username() string { + current.mu.Lock() + defer current.mu.Unlock() + return current.user +} + +func (server *Server) addCloser(closer io.Closer) { + server.mu.Lock() + server.closers = append(server.closers, closer) + server.mu.Unlock() +} + +func (server *Server) isClosed() bool { + select { + case <-server.closed: + return true + default: + return false + } +} + +func (server *Server) Close() error { + var closeError error + server.closeOnce.Do(func() { + close(server.closed) + server.mu.RLock() + closers := append([]io.Closer(nil), server.closers...) + sessions := make([]*session, 0, len(server.sessions)) + for current := range server.sessions { + sessions = append(sessions, current) + } + server.mu.RUnlock() + for _, closer := range closers { + if err := closer.Close(); err != nil && closeError == nil && !errors.Is(err, net.ErrClosed) { + closeError = err + } + } + for _, current := range sessions { + current.close() + } + if err := server.tun.Close(); err != nil && closeError == nil && !errors.Is(err, os.ErrClosed) { + closeError = err + } + }) + return closeError +} + +func (server *Server) Wait() { server.wait.Wait() } + +func (server *Server) Stats() StatsSnapshot { + return StatsSnapshot{ + StartedAt: server.started, ActiveSessions: server.stats.activeSessions.Load(), + Accepted: server.stats.accepted.Load(), AuthSucceeded: server.stats.authSucceeded.Load(), + AuthRejected: server.stats.authRejected.Load(), ClientPackets: server.stats.clientPackets.Load(), + InternetPackets: server.stats.internetPackets.Load(), ClientBytes: server.stats.clientBytes.Load(), + InternetBytes: server.stats.internetBytes.Load(), DroppedPackets: server.stats.droppedPackets.Load(), + SessionsRejected: server.stats.sessionsRejected.Load(), + } +} + +func writeFull(writer io.Writer, data []byte) error { + for len(data) > 0 { + written, err := writer.Write(data) + if err != nil { + return err + } + if written == 0 { + return io.ErrShortWrite + } + data = data[written:] + } + return nil +} + +func normalClose(err error) bool { + if err == nil || errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) { + return true + } + var networkError net.Error + if errors.As(err, &networkError) && networkError.Timeout() { + return true + } + message := strings.ToLower(err.Error()) + return strings.Contains(message, "connection reset") || strings.Contains(message, "broken pipe") +} diff --git a/internal/btun/server_test.go b/internal/btun/server_test.go new file mode 100644 index 0000000..93d9e74 --- /dev/null +++ b/internal/btun/server_test.go @@ -0,0 +1,253 @@ +package btun + +import ( + "bytes" + "encoding/binary" + "io" + "log" + "net" + "sync" + "testing" + "time" +) + +type fakeTUN struct { + reads chan []byte + writes chan []byte + closed chan struct{} + once sync.Once +} + +func newFakeTUN() *fakeTUN { + return &fakeTUN{reads: make(chan []byte, 4), writes: make(chan []byte, 4), closed: make(chan struct{})} +} + +func (tun *fakeTUN) Name() string { return "test0" } +func (tun *fakeTUN) Read(buffer []byte) (int, error) { + select { + case packet := <-tun.reads: + return copy(buffer, packet), nil + case <-tun.closed: + return 0, io.EOF + } +} +func (tun *fakeTUN) Write(packet []byte) (int, error) { + copyOfPacket := append([]byte(nil), packet...) + select { + case tun.writes <- copyOfPacket: + return len(packet), nil + case <-tun.closed: + return 0, io.ErrClosedPipe + } +} +func (tun *fakeTUN) Close() error { + tun.once.Do(func() { close(tun.closed) }) + return nil +} + +func TestTCPAuthenticationAndPacketRouting(t *testing.T) { + tun := newFakeTUN() + server, err := NewServer(Config{ + Subnet: "10.77.0.0/29", Authenticator: AllowAuthenticator{}, + Logger: log.New(io.Discard, "", 0), HandshakeTimeout: time.Second, + IdleTimeout: time.Minute, + }, tun) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = server.Close() + server.Wait() + }) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + serveDone := make(chan error, 1) + go func() { serveDone <- server.ServeTCP(listener) }() + connection, err := net.DialTimeout("tcp", listener.Addr().String(), time.Second) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(2 * time.Second)) + + if _, err := connection.Write(append([]byte("cover request\r\n"), ClientHello...)); err != nil { + t.Fatal(err) + } + hello := make([]byte, len(ServerHello)) + if _, err := io.ReadFull(connection, hello); err != nil { + t.Fatal(err) + } + if !bytes.Equal(hello, ServerHello) { + t.Fatalf("server hello = %q", hello) + } + writeTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")}) + auth := readTestPacket(t, connection) + if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 { + t.Fatalf("unexpected auth response: %#v", auth) + } + writeTestPacket(t, connection, Packet{Type: PacketIP}) + ipResponse := readTestPacket(t, connection) + if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 { + t.Fatalf("unexpected IP response: %#v", ipResponse) + } + assigned := net.IP(ipResponse.Payload) + // DT5 may emit a non-IPv4 frame while its TUN is coming up. The server + // must drop it without destroying the authenticated stream. + writeTestPacket(t, connection, Packet{Type: PacketData, Payload: []byte{0x60, 0, 0, 0}}) + outbound := ipv4Packet(assigned, net.IPv4(1, 1, 1, 1), []byte("out")) + writeTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound}) + select { + case got := <-tun.writes: + if !bytes.Equal(got, outbound) { + t.Fatal("outbound TUN packet mismatch") + } + case <-time.After(time.Second): + t.Fatal("outbound packet did not reach TUN") + } + inbound := ipv4Packet(net.IPv4(1, 1, 1, 1), assigned, []byte("in")) + tun.reads <- inbound + data := readTestPacket(t, connection) + if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) { + t.Fatalf("unexpected inbound packet: %#v", data) + } + + _ = server.Close() + server.Wait() + if err := <-serveDone; err != nil { + t.Fatal(err) + } +} + +func TestUDPAuthenticationAndPacketRouting(t *testing.T) { + tun := newFakeTUN() + server, err := NewServer(Config{ + Subnet: "10.77.1.0/29", Authenticator: AllowAuthenticator{}, + Logger: log.New(io.Discard, "", 0), IdleTimeout: time.Minute, + }, tun) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = server.Close() + server.Wait() + }) + packetConnection, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + serveDone := make(chan error, 1) + go func() { serveDone <- server.ServeUDP(packetConnection) }() + connection, err := net.Dial("udp", packetConnection.LocalAddr().String()) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(2 * time.Second)) + + if _, err := connection.Write(ClientHello); err != nil { + t.Fatal(err) + } + hello := make([]byte, len(ServerHello)) + if _, err := io.ReadFull(connection, hello); err != nil { + t.Fatal(err) + } + if !bytes.Equal(hello, ServerHello) { + t.Fatalf("server hello = %q", hello) + } + writeUDPTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")}) + auth := readUDPTestPacket(t, connection) + if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 { + t.Fatalf("unexpected auth response: %#v", auth) + } + writeUDPTestPacket(t, connection, Packet{Type: PacketIP}) + ipResponse := readUDPTestPacket(t, connection) + if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 { + t.Fatalf("unexpected IP response: %#v", ipResponse) + } + assigned := net.IP(ipResponse.Payload) + outbound := ipv4Packet(assigned, net.IPv4(8, 8, 8, 8), []byte("udp-out")) + writeUDPTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound}) + select { + case got := <-tun.writes: + if !bytes.Equal(got, outbound) { + t.Fatal("outbound UDP TUN packet mismatch") + } + case <-time.After(time.Second): + t.Fatal("outbound UDP packet did not reach TUN") + } + inbound := ipv4Packet(net.IPv4(8, 8, 8, 8), assigned, []byte("udp-in")) + tun.reads <- inbound + data := readUDPTestPacket(t, connection) + if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) { + t.Fatalf("unexpected inbound UDP packet: %#v", data) + } + + _ = server.Close() + server.Wait() + if err := <-serveDone; err != nil { + t.Fatal(err) + } +} + +func writeTestPacket(t *testing.T, writer io.Writer, packet Packet) { + t.Helper() + encoded, err := MarshalPacket(packet, DefaultMaxPacket) + if err != nil { + t.Fatal(err) + } + if err := writeFull(writer, encoded); err != nil { + t.Fatal(err) + } +} + +func readTestPacket(t *testing.T, reader io.Reader) Packet { + t.Helper() + packet, err := ReadPacket(reader, DefaultMaxPacket) + if err != nil { + t.Fatal(err) + } + return packet +} + +func writeUDPTestPacket(t *testing.T, writer io.Writer, packet Packet) { + t.Helper() + encoded, err := MarshalPacket(packet, DefaultMaxPacket) + if err != nil { + t.Fatal(err) + } + written, err := writer.Write(encoded) + if err != nil { + t.Fatal(err) + } + if written != len(encoded) { + t.Fatal(io.ErrShortWrite) + } +} + +func readUDPTestPacket(t *testing.T, reader io.Reader) Packet { + t.Helper() + buffer := make([]byte, DefaultMaxPacket+HeaderSize) + length, err := reader.Read(buffer) + if err != nil { + t.Fatal(err) + } + packet, err := ParseDatagram(buffer[:length], DefaultMaxPacket) + if err != nil { + t.Fatal(err) + } + return packet +} + +func ipv4Packet(source, destination net.IP, payload []byte) []byte { + packet := make([]byte, 20+len(payload)) + packet[0] = 0x45 + binary.BigEndian.PutUint16(packet[2:4], uint16(len(packet))) + packet[8] = 64 + packet[9] = 17 + copy(packet[12:16], source.To4()) + copy(packet[16:20], destination.To4()) + copy(packet[20:], payload) + return packet +} diff --git a/internal/btun/sniff.go b/internal/btun/sniff.go new file mode 100644 index 0000000..2435082 --- /dev/null +++ b/internal/btun/sniff.go @@ -0,0 +1,47 @@ +package btun + +import "bytes" + +// Verdict is the result of inspecting the first bytes of a connection. +type Verdict int + +const ( + // VerdictNo means the bytes cannot begin a BTUN handshake. + VerdictNo Verdict = iota + // VerdictMore means the bytes so far are consistent with one but more are + // needed to decide. The caller should peek further and ask again. + VerdictMore + // VerdictYes means the bytes begin a BTUN handshake. + VerdictYes +) + +// SniffLimit is the largest number of bytes SniffClientHello ever needs. +var SniffLimit = len(ClientHello) + +// SniffClientHello reports whether data begins with the BTUN client hello, so +// a listener shared with other protocols can route the connection without +// consuming anything. +// +// The hello is a fixed 25-byte ASCII marker, which makes this decisive in a +// way a length or range check never is: no SSH identification and no HTTP +// request line can match it, and the very first byte already rejects both in +// the overwhelming majority of cases. +// +// The match is anchored at offset zero. A TCP client may legitimately prepend +// cover bytes before its hello, and ServeTCP still tolerates that on a +// dedicated BTUN port, but a shared port cannot buffer an unbounded prefix +// while some other protocol waits to be recognised. Cover that is itself an +// HTTP request is still handled: the panel's HTTP cleanup consumes it, which +// leaves the hello at offset zero for a second look. +func SniffClientHello(data []byte) Verdict { + if len(data) >= len(ClientHello) { + if bytes.Equal(data[:len(ClientHello)], ClientHello) { + return VerdictYes + } + return VerdictNo + } + if bytes.Equal(data, ClientHello[:len(data)]) { + return VerdictMore + } + return VerdictNo +} diff --git a/internal/btun/sniff_test.go b/internal/btun/sniff_test.go new file mode 100644 index 0000000..63a7d27 --- /dev/null +++ b/internal/btun/sniff_test.go @@ -0,0 +1,46 @@ +package btun + +import "testing" + +// Everything BTUN shares a port with has to be rejected, and the marker itself +// has to be accepted, or sharing the port would break SSH and HTTP clients. +func TestSniffClientHello(t *testing.T) { + tests := []struct { + name string + input string + want Verdict + }{ + {name: "exact marker", input: string(ClientHello), want: VerdictYes}, + {name: "marker then payload", input: string(ClientHello) + "\x01\x02", want: VerdictYes}, + {name: "partial marker", input: "DTUNNEL/1.1 CLI", want: VerdictMore}, + {name: "first byte only", input: "D", want: VerdictMore}, + {name: "empty", input: "", want: VerdictMore}, + {name: "SSH identification", input: "SSH-2.0-OpenSSH_9.6\r\n", want: VerdictNo}, + {name: "HTTP GET", input: "GET / HTTP/1.1\r\n\r\n", want: VerdictNo}, + {name: "HTTP DELETE shares a first byte", input: "DELETE / HTTP/1.1\r\n\r\n", want: VerdictNo}, + {name: "TLS client hello", input: "\x16\x03\x01\x02\x00", want: VerdictNo}, + {name: "BHTTP frame", input: "\x00\x01\x02\x03", want: VerdictNo}, + {name: "wrong version", input: "DTUNNEL/2.0 CLIENT_HELLO\r\n", want: VerdictNo}, + {name: "marker not at offset zero", input: "xxDTUNNEL/1.1 CLIENT_HELLO\r\n", want: VerdictNo}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := SniffClientHello([]byte(tt.input)); got != tt.want { + t.Fatalf("SniffClientHello(%q) = %v, want %v", tt.input, got, tt.want) + } + }) + } +} + +// A partial marker must never be mistaken for a complete one, however it is +// split across reads. +func TestSniffClientHelloIsProgressive(t *testing.T) { + for cut := 0; cut < len(ClientHello); cut++ { + if got := SniffClientHello(ClientHello[:cut]); got != VerdictMore { + t.Fatalf("SniffClientHello(first %d bytes) = %v, want VerdictMore", cut, got) + } + } + if got := SniffClientHello(ClientHello); got != VerdictYes { + t.Fatalf("SniffClientHello(full marker) = %v, want VerdictYes", got) + } +} diff --git a/internal/btun/tun_linux.go b/internal/btun/tun_linux.go new file mode 100644 index 0000000..da8e4b4 --- /dev/null +++ b/internal/btun/tun_linux.go @@ -0,0 +1,164 @@ +//go:build linux + +package btun + +import ( + "bytes" + "fmt" + "io" + "os" + "sync" + "syscall" + "time" + "unsafe" +) + +const ( + tunSetIFF = 0x400454ca + iffTUN = 0x0001 + iffNoPI = 0x1000 +) + +type linuxTUN struct { + file *os.File + fd int + name string + closed chan struct{} + readerDone chan struct{} + packets chan []byte + readErrors chan error + fdMu sync.RWMutex + closeOnce sync.Once + closeErr error +} + +func OpenTUN(requestedName string) (PacketDevice, error) { + if len(requestedName) == 0 || len(requestedName) >= 16 { + return nil, fmt.Errorf("invalid TUN interface name %q", requestedName) + } + file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0) + if err != nil { + return nil, fmt.Errorf("open /dev/net/tun: %w", err) + } + var request [40]byte + copy(request[:16], requestedName) + *(*uint16)(unsafe.Pointer(&request[16])) = iffTUN | iffNoPI + fd := int(file.Fd()) + _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), tunSetIFF, uintptr(unsafe.Pointer(&request[0]))) + if errno != 0 { + file.Close() + return nil, fmt.Errorf("TUNSETIFF %s: %w", requestedName, errno) + } + if err := syscall.SetNonblock(fd, true); err != nil { + file.Close() + return nil, fmt.Errorf("set TUN nonblocking: %w", err) + } + nameLength := bytes.IndexByte(request[:16], 0) + if nameLength < 0 { + nameLength = 16 + } + actual := string(request[:nameLength]) + tun := &linuxTUN{ + file: file, fd: fd, name: actual, closed: make(chan struct{}), + readerDone: make(chan struct{}), packets: make(chan []byte, 64), + readErrors: make(chan error, 1), + } + go tun.readLoop() + return tun, nil +} + +func (tun *linuxTUN) Read(buffer []byte) (int, error) { + select { + case packet := <-tun.packets: + if len(packet) > len(buffer) { + return 0, io.ErrShortBuffer + } + return copy(buffer, packet), nil + case err := <-tun.readErrors: + return 0, err + case <-tun.closed: + return 0, os.ErrClosed + } +} + +func (tun *linuxTUN) readLoop() { + defer close(tun.readerDone) + buffer := make([]byte, DefaultMaxPacket) + for { + select { + case <-tun.closed: + return + default: + } + tun.fdMu.RLock() + length, err := syscall.Read(tun.fd, buffer) + tun.fdMu.RUnlock() + if err == nil && length > 0 { + packet := append([]byte(nil), buffer[:length]...) + select { + case tun.packets <- packet: + case <-tun.closed: + return + } + continue + } + if err == nil { + continue + } + if err == syscall.EINTR { + continue + } + if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK { + select { + case tun.readErrors <- err: + case <-tun.closed: + } + return + } + select { + case <-tun.closed: + return + case <-time.After(25 * time.Millisecond): + } + } +} + +func (tun *linuxTUN) Write(buffer []byte) (int, error) { + for { + select { + case <-tun.closed: + return 0, os.ErrClosed + default: + } + tun.fdMu.RLock() + length, err := syscall.Write(tun.fd, buffer) + tun.fdMu.RUnlock() + if err == nil { + return length, nil + } + if err == syscall.EINTR { + continue + } + if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK { + return 0, err + } + select { + case <-tun.closed: + return 0, os.ErrClosed + case <-time.After(25 * time.Millisecond): + } + } +} + +func (tun *linuxTUN) Close() error { + tun.closeOnce.Do(func() { + close(tun.closed) + <-tun.readerDone + tun.fdMu.Lock() + tun.closeErr = tun.file.Close() + tun.fdMu.Unlock() + }) + return tun.closeErr +} + +func (tun *linuxTUN) Name() string { return tun.name } diff --git a/internal/btun/tun_stub.go b/internal/btun/tun_stub.go new file mode 100644 index 0000000..e50f257 --- /dev/null +++ b/internal/btun/tun_stub.go @@ -0,0 +1,9 @@ +//go:build !linux + +package btun + +import "errors" + +func OpenTUN(_ string) (PacketDevice, error) { + return nil, errors.New("BTUN TUN is only supported on Linux") +} diff --git a/internal/hcr/server.go b/internal/hcr/server.go new file mode 100644 index 0000000..2736030 --- /dev/null +++ b/internal/hcr/server.go @@ -0,0 +1,1182 @@ +package hcr + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "net" + "sync" + "sync/atomic" + "time" +) + +// ============================================================================ +// HCR SERVER (0.0.3 - Patch 1) - RECONSTRUÇÃO EM GOLANG +// +// O HCR (HTTP/Custom Relay) atua como servidor proxy/túnel de alta performance +// para o ecossistema UDP-Custom / HTTP Custom. O protocolo encapsula fluxos +// arbitrários de rede (tipicamente conexões SSH no alvo 127.0.0.1:22) em pacotes +// binários estruturados sobre TCP ou TLS (porta padrão :8880). +// +// ESTRUTURA DO PROTOCOLO BINÁRIO REVERSO: +// 1. Requisição do Cliente (Client Request Header) - 62 bytes fixos: +// - [0:1] Code (uint8): Código da operação (1..6) +// - [1:2] Version (uint8): Versão do protocolo (deve ser 0x01) +// - [2:18] SessionID ([16]byte): Identificador UUID da sessão +// - [18:50] AuthKey ([32]byte): Token de autenticação / PSK +// - [50:58] Sequence (uint64 BigEndian): Offset de sequência de stream +// - [58:62] PayloadLen (uint32 BigEndian): Tamanho do payload subsequente +// - [62:] Payload ([]byte): Dados da requisição +// +// 2. Resposta do Servidor (Server Response Header) - 14 bytes fixos: +// - [0:1] Status (uint8): 0=OK, 3=Closed, 4=Error +// - [1:2] Version (uint8): Versão do protocolo (0x01) +// - [2:10] Sequence (uint64 BigEndian): Offset de sequência confirmado +// - [10:14] PayloadLen (uint32 BigEndian): Tamanho do payload de resposta +// - [14:] Payload ([]byte): Dados da resposta +// ============================================================================ + +const ( + VersionString = "0.0.3 - Patch 1" + ProtoVersion = 1 + + // Tamanhos dos cabeçalhos binários + RequestHeaderSize = 62 // 1 + 1 + 16 + 32 + 8 + 4 + ResponseHeaderSize = 14 // 1 + 1 + 8 + 4 + + // Limite máximo de frame por payload (256 KB) deduzido de FUN_0065c580 (0x40000) + MaxPayloadLimit = 262144 +) + +// Códigos de Requisição (Request Codes) +const ( + ReqConnect uint8 = 1 // Inicia nova sessão e conecta ao alvo + ReqData uint8 = 2 // Envia dados do cliente para o alvo (Upload) + ReqPoll uint8 = 3 // Solicita dados recebidos do alvo (Download/Long-polling) + ReqAck uint8 = 4 // Confirmação de recebimento pelo cliente até Sequence + ReqClose uint8 = 5 // Encerra explicitamente a sessão + ReqPing uint8 = 6 // Keepalive / Checagem de status da sessão +) + +// Códigos de Resposta (Response Status Codes) +const ( + StatusOk uint8 = 0 // Operação bem-sucedida (ReqConnect, ReqData, ReqAck, ReqPing) + StatusPollData uint8 = 1 // Download com dados entregues (ReqPoll, FUN_00664300 linha 345282) + StatusPollTimeout uint8 = 2 // Long-poll expirado sem dados no intervalo (ReqPoll, FUN_00664300 linha 345408) + StatusClosed uint8 = 3 // Sessão ou conexão com o alvo encerrada (FUN_00664300 linha 345311) + StatusError uint8 = 4 // Erro / Requisição rejeitada +) + +// Erros do Protocolo +var ( + ErrInvalidRequest = errors.New("INVALID_REQUEST") + ErrAuthFailed = errors.New("AUTH_FAILED") + ErrTargetBroken = errors.New("TARGET_BROKEN") + ErrTargetUnavail = errors.New("target_unavailable") + ErrGlobalLimit = errors.New("global_session_limit") + ErrSourceLimit = errors.New("source_session_limit") + ErrAckInvalid = errors.New("ACK_INVALID") + ErrSessionCollision = errors.New("session_id_collision") +) + +// Direções do Fluxo para Cifra de Payload (de FUN_0065d160 em hcr.c) +const ( + DirRequest uint8 = 0 // Cliente -> Servidor (Request payload) + DirResponse uint8 = 1 // Servidor -> Cliente (Response payload) +) + +// maskPayload aplica a cifra de fluxo simétrica (CTR-mode com SHA-256) no payload +// conforme a implementação reversa da função FUN_0065d160 em hcr.c. +// Semente de 30 bytes: +// [0:16] SessionID (16 bytes) +// [16] Code (uint8) +// [17:25] Sequence (uint64 BigEndian) +// [25] Direction (uint8: 1=Req, 2=Resp) +// [26:30] BlockIndex (uint32 BigEndian) +func maskPayload(payload []byte, sessionID [16]byte, code uint8, seq uint64, direction uint8) { + pLen := len(payload) + if pLen == 0 { + return + } + var seed [30]byte + copy(seed[0:16], sessionID[:]) + seed[16] = code + binary.BigEndian.PutUint64(seed[17:25], seq) + seed[25] = direction + + for offset := 0; offset < pLen; offset += 32 { + blockIndex := uint32(offset / 32) + binary.BigEndian.PutUint32(seed[26:30], blockIndex) + block := sha256.Sum256(seed[:]) + chunkLen := 32 + if pLen-offset < 32 { + chunkLen = pLen - offset + } + p := payload[offset : offset+chunkLen] + b := block[:chunkLen] + rem := chunkLen + for rem >= 8 { + v1 := binary.LittleEndian.Uint64(p) + v2 := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(p, v1^v2) + p = p[8:] + b = b[8:] + rem -= 8 + } + for i := 0; i < rem; i++ { + p[i] ^= b[i] + } + } +} + +// Config holds the HCR engine settings. The panel owns the listeners and TLS, +// so this carries no listen address, transport or certificate: the integration +// hands the engine an already-accepted connection (ServeConn) or a plain +// listener (Serve). +type Config struct { + // TargetAddr is dialed for each session when DialTarget is nil. In the + // panel this stays empty and DialTarget points at the built-in SSH server. + TargetAddr string + // DialTarget, when set, supplies the per-session target connection. The + // panel uses it to hand every HCR session to its own in-process SSH server, + // so HCR logins are panel accounts with the usual limits — no system sshd. + DialTarget func() (net.Conn, error) + // Logger receives engine events. Nil uses a discard logger. + Logger *slog.Logger + + MaxConnections int + MaxSessions int + MaxSourceSessions int + DownloadPollTimeout time.Duration + MaxDownloadFrame int + IdleSessionTimeout time.Duration +} + +func minInt(a, b int) int { + if a < b { + return a + } + return b +} + +func shortID(id [16]byte) string { + return hex.EncodeToString(id[:4]) +} + +func reqCodeNameShort(c uint8) string { + switch c { + case ReqConnect: + return "Connect" + case ReqData: + return "Data" + case ReqPoll: + return "Poll" + case ReqAck: + return "Ack" + case ReqClose: + return "Close" + case ReqPing: + return "Ping" + default: + return fmt.Sprintf("Code(%d)", c) + } +} + +func statusCodeNameShort(s uint8) string { + switch s { + case StatusOk: + return "Ok(0)" + case StatusPollData: + return "PollData(1)" + case StatusPollTimeout: + return "PollTimeout(2)" + case StatusClosed: + return "Closed(3)" + case StatusError: + return "Error(4)" + default: + return fmt.Sprintf("Status(%d)", s) + } +} + +func reqCodeName(c uint8) string { + return reqCodeNameShort(c) +} + +func statusCodeName(s uint8) string { + return statusCodeNameShort(s) +} + +// RequestHeader representa o cabeçalho de 62 bytes enviado pelo cliente +type RequestHeader struct { + Code uint8 + Version uint8 + SessionID [16]byte + AuthKey [32]byte + Sequence uint64 + PayloadLen uint32 +} + +// ResponseHeader representa o cabeçalho de 14 bytes enviado pelo servidor +type ResponseHeader struct { + Status uint8 + Version uint8 + Sequence uint64 + PayloadLen uint32 +} + +// UnmarshalRequestHeader lê e decodifica os 62 bytes fixos da requisição +func UnmarshalRequestHeader(buf []byte) (*RequestHeader, error) { + if len(buf) < RequestHeaderSize { + return nil, io.ErrUnexpectedEOF + } + code := buf[0] + if code < 1 || code > 6 { + return nil, ErrInvalidRequest + } + version := buf[1] + if version != ProtoVersion { + return nil, ErrInvalidRequest + } + + h := &RequestHeader{ + Code: code, + Version: version, + Sequence: binary.BigEndian.Uint64(buf[50:58]), + PayloadLen: binary.BigEndian.Uint32(buf[58:62]), + } + copy(h.SessionID[:], buf[2:18]) + copy(h.AuthKey[:], buf[18:50]) + + if h.PayloadLen > MaxPayloadLimit { + return nil, ErrInvalidRequest + } + return h, nil +} + +// MarshalResponseHeader serializa o cabeçalho de 14 bytes do servidor +func MarshalResponseHeader(status uint8, seq uint64, payloadLen uint32) []byte { + buf := make([]byte, ResponseHeaderSize) + buf[0] = status + buf[1] = ProtoVersion + binary.BigEndian.PutUint64(buf[2:10], seq) + binary.BigEndian.PutUint32(buf[10:14], payloadLen) + return buf +} + +// DownloadFrame armazena um pedaço de dados vindo do alvo para entrega ao cliente +type DownloadFrame struct { + Seq uint64 + Data []byte +} + +// Session mantém o estado do túnel entre o cliente HCR e a conexão TCP com o alvo +type Session struct { + ID [16]byte + SourceIP string + Target net.Conn + CreatedAt time.Time + + mu sync.Mutex + + // Controle de escrita no alvo (Upload) + targetClosed bool + targetWriteCh chan []byte // Fila assíncrona FIFO para escrita contínua no alvo + writeSeq uint64 // Próximo pacote de upload esperado do cliente (0, 1, 2, ...) + upBuffer map[uint64][]byte // Buffer de upload para pacotes recebidos fora de ordem + + // Controle de leitura do alvo (Download/Poll) + cond *sync.Cond + dataNotify chan struct{} // Canal de broadcast (fechado para acordar todos os polls simultâneos) + downBuffer []*DownloadFrame + downSeq uint64 // Próximo offset a ser atribuído para dados lidos do alvo + ackSeq uint64 // Offset confirmado pelo cliente via REQ_ACK + hasAcked bool // Indica se o cliente já enviou ao menos um ACK + deliveredSeq uint64 // Maior offset entregue ao cliente + pendingBytes int // Total de bytes acumulados no buffer de download + maxFrame int // Tamanho máximo por frame lido do alvo + + lastActive atomic.Int64 // Unix nanoseconds +} + +// notifyDataLocked fecha o canal de notificação atual (acordando todos os workers de poll em broadcast) +// e cria um novo canal vazio. DEVE ser chamado com s.mu bloqueado. +func (s *Session) notifyDataLocked() { + if s.dataNotify != nil { + close(s.dataNotify) + s.dataNotify = make(chan struct{}) + } +} + +func (s *Session) touch() { + s.lastActive.Store(time.Now().UnixNano()) +} + +func (s *Session) isIdle(timeout time.Duration) bool { + last := s.lastActive.Load() + return time.Since(time.Unix(0, last)) > timeout +} + +func (s *Session) hasFramesFrom(seq uint64) bool { + if len(s.downBuffer) == 0 { + return false + } + firstSeq := s.downBuffer[0].Seq + lastSeq := s.downBuffer[len(s.downBuffer)-1].Seq + return seq >= firstSeq && seq <= lastSeq +} + +func (s *Session) getFramesFrom(startSeq uint64, maxChunks int, maxBytes int) []*DownloadFrame { + if len(s.downBuffer) == 0 { + return nil + } + firstSeq := s.downBuffer[0].Seq + if startSeq < firstSeq { + return nil + } + startIndex := int(startSeq - firstSeq) + if startIndex >= len(s.downBuffer) { + return nil + } + var result []*DownloadFrame + totalBytes := 0 + for i := startIndex; i < len(s.downBuffer) && len(result) < maxChunks; i++ { + f := s.downBuffer[i] + frameBytes := len(f.Data) + 4 + if len(result) > 0 && totalBytes+frameBytes > maxBytes { + break + } + result = append(result, f) + totalBytes += frameBytes + } + return result +} + +// SessionManager gerencia o ciclo de vida e limites das sessões ativas +type SessionManager struct { + mu sync.RWMutex + sessions map[[16]byte]*Session + sourceCount map[string]int + + cfg *Config + logger *slog.Logger +} + +func NewSessionManager(cfg *Config, logger *slog.Logger) *SessionManager { + return &SessionManager{ + sessions: make(map[[16]byte]*Session), + sourceCount: make(map[string]int), + cfg: cfg, + logger: logger, + } +} + +func (m *SessionManager) CreateSession(id [16]byte, sourceIP string) (*Session, error) { + m.mu.Lock() + defer m.mu.Unlock() + + // Validação de colisão de ID + if _, exists := m.sessions[id]; exists { + return nil, ErrSessionCollision + } + + // Validação de limite global de sessões + if m.cfg.MaxSessions > 0 && len(m.sessions) >= m.cfg.MaxSessions { + return nil, ErrGlobalLimit + } + + // Validação de limite de sessões por IP de origem + if m.cfg.MaxSourceSessions > 0 { + if count := m.sourceCount[sourceIP]; count >= m.cfg.MaxSourceSessions { + return nil, ErrSourceLimit + } + } + + // Open the per-session target. In the panel this is the built-in SSH server + // (DialTarget); standalone it dials TargetAddr over TCP. + var targetConn net.Conn + var err error + if m.cfg.DialTarget != nil { + targetConn, err = m.cfg.DialTarget() + } else { + targetConn, err = net.DialTimeout("tcp", m.cfg.TargetAddr, 5*time.Second) + } + if err != nil { + m.logger.Warn("target_unavailable", "target", m.cfg.TargetAddr, "err", err) + return nil, ErrTargetUnavail + } + + if tcpConn, ok := targetConn.(*net.TCPConn); ok { + _ = tcpConn.SetNoDelay(true) + _ = tcpConn.SetReadBuffer(1024 * 1024) + _ = tcpConn.SetWriteBuffer(1024 * 1024) + _ = tcpConn.SetKeepAlive(true) + _ = tcpConn.SetKeepAlivePeriod(30 * time.Second) + } + + maxFrame := m.cfg.MaxDownloadFrame + if maxFrame <= 0 || maxFrame > 16384 { + maxFrame = 16384 + } + + sess := &Session{ + ID: id, + SourceIP: sourceIP, + Target: targetConn, + CreatedAt: time.Now(), + dataNotify: make(chan struct{}), + targetWriteCh: make(chan []byte, 2048), + upBuffer: make(map[uint64][]byte), + maxFrame: maxFrame, + } + sess.cond = sync.NewCond(&sess.mu) + sess.touch() + + m.sessions[id] = sess + m.sourceCount[sourceIP]++ + + // Goroutines assíncronas para streaming com o alvo (Upload e Download desacoplados) + go m.writeTargetLoop(sess) + go m.readTargetLoop(sess) + + return sess, nil +} + +// writeTargetLoop consome continuamente a fila de upload e grava no alvo TCP de forma sequencial +func (m *SessionManager) writeTargetLoop(s *Session) { + for data := range s.targetWriteCh { + if len(data) == 0 { + continue + } + if _, err := s.Target.Write(data); err != nil { + s.mu.Lock() + if !s.targetClosed { + s.targetClosed = true + s.notifyDataLocked() + } + s.mu.Unlock() + break + } + } +} + +func (m *SessionManager) GetSession(id [16]byte) (*Session, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + sess, ok := m.sessions[id] + return sess, ok +} + +// Len reports how many sessions are currently tracked. +func (m *SessionManager) Len() int64 { + m.mu.RLock() + defer m.mu.RUnlock() + return int64(len(m.sessions)) +} + +func (m *SessionManager) CloseSession(id [16]byte) { + m.mu.Lock() + sess, ok := m.sessions[id] + if !ok { + m.mu.Unlock() + return + } + delete(m.sessions, id) + if m.sourceCount[sess.SourceIP] > 0 { + m.sourceCount[sess.SourceIP]-- + if m.sourceCount[sess.SourceIP] == 0 { + delete(m.sourceCount, sess.SourceIP) + } + } + m.mu.Unlock() + + sess.mu.Lock() + if !sess.targetClosed { + sess.targetClosed = true + sess.Target.Close() + sess.notifyDataLocked() + } + sess.mu.Unlock() +} + +// CloseAll encerra todas as conexões de sessões ativas (durante o shutdown do servidor) +func (m *SessionManager) CloseAll() { + m.mu.Lock() + var toClose []*Session + for _, sess := range m.sessions { + toClose = append(toClose, sess) + } + m.sessions = make(map[[16]byte]*Session) + m.sourceCount = make(map[string]int) + m.mu.Unlock() + + for _, sess := range toClose { + sess.mu.Lock() + if !sess.targetClosed { + sess.targetClosed = true + sess.Target.Close() + sess.notifyDataLocked() + } + sess.mu.Unlock() + } +} + +// readTargetLoop lê os dados enviados pelo servidor alvo (ex: banner SSH) e enfileira no buffer de download +func (m *SessionManager) readTargetLoop(s *Session) { + buf := make([]byte, s.maxFrame) + for { + // Controle de fluxo de 4MB (FUN_0065e1a0 em hcr.c): + // Se pendingBytes >= 4MB, aguarda no broadcast do canal até que ACKs liberem espaço + s.mu.Lock() + for s.pendingBytes >= 4*1024*1024 && !s.targetClosed { + notifyCh := s.dataNotify + s.mu.Unlock() + <-notifyCh + s.mu.Lock() + } + if s.targetClosed { + s.mu.Unlock() + break + } + readSize := s.maxFrame + if remain := 4*1024*1024 - s.pendingBytes; remain < readSize { + readSize = remain + } + s.mu.Unlock() + + n, err := s.Target.Read(buf[:readSize]) + if n > 0 { + s.mu.Lock() + dataCopy := make([]byte, n) + copy(dataCopy, buf[:n]) + + frame := &DownloadFrame{ + Seq: s.downSeq, + Data: dataCopy, + } + s.downBuffer = append(s.downBuffer, frame) + s.downSeq++ + s.pendingBytes += n + s.touch() + s.notifyDataLocked() + s.mu.Unlock() + } + if err != nil { + s.mu.Lock() + s.targetClosed = true + s.notifyDataLocked() + s.mu.Unlock() + break + } + } +} + +// ReapIdleSessions limpa sessões inativas periodicamente +func (m *SessionManager) ReapIdleSessions() int { + var toClose [][16]byte + + m.mu.RLock() + for id, sess := range m.sessions { + if sess.isIdle(m.cfg.IdleSessionTimeout) { + toClose = append(toClose, id) + } + } + m.mu.RUnlock() + + for _, id := range toClose { + m.CloseSession(id) + } + return len(toClose) +} + +// ============================================================================ +// HCR Server Core +// ============================================================================ + +// ---------- Stats ---------- + +type counters struct { + accepted atomic.Uint64 + connectionsReject atomic.Uint64 + activeConns atomic.Int64 + sessionsCreated atomic.Uint64 + sessionsRejected atomic.Uint64 + uploadBytes atomic.Uint64 + downloadBytes atomic.Uint64 + protocolErrors atomic.Uint64 +} + +// StatsSnapshot is what the admin panel reads. +type StatsSnapshot struct { + StartedAt time.Time `json:"startedAt"` + ActiveConnections int64 `json:"activeConnections"` + ActiveSessions int64 `json:"activeSessions"` + Accepted uint64 `json:"accepted"` + ConnectionsRejected uint64 `json:"connectionsRejected"` + SessionsCreated uint64 `json:"sessionsCreated"` + SessionsRejected uint64 `json:"sessionsRejected"` + UploadBytes uint64 `json:"uploadBytes"` + DownloadBytes uint64 `json:"downloadBytes"` + ProtocolErrors uint64 `json:"protocolErrors"` +} + +// Server is the embeddable HCR engine. The panel owns listeners and TLS; the +// server only speaks the plaintext HCR frame protocol on a connection handed to +// Serve or ServeConn. +type Server struct { + cfg *Config + sessions *SessionManager + logger *slog.Logger + sem chan struct{} + started time.Time + stats counters + + closed chan struct{} + closeOnce sync.Once + wait sync.WaitGroup +} + +// NewServer builds an HCR engine. Logger defaults to a discard logger. +func NewServer(cfg *Config) *Server { + logger := cfg.Logger + if logger == nil { + logger = slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelInfo})) + } + if cfg.DownloadPollTimeout <= 0 { + cfg.DownloadPollTimeout = 10 * time.Second + } + if cfg.IdleSessionTimeout <= 0 { + cfg.IdleSessionTimeout = 5 * time.Minute + } + var sem chan struct{} + if cfg.MaxConnections > 0 { + sem = make(chan struct{}, cfg.MaxConnections) + } + return &Server{ + cfg: cfg, + sessions: NewSessionManager(cfg, logger), + logger: logger, + sem: sem, + started: time.Now(), + closed: make(chan struct{}), + } +} + +// Serve accepts plaintext HCR connections on a listener the panel owns. TLS, if +// any, is terminated by the panel's TLS forwarder before this point. +func (s *Server) Serve(ctx context.Context, listener net.Listener) error { + s.wait.Add(1) + defer s.wait.Done() + go s.idleReaperLoop(ctx) + for { + conn, err := listener.Accept() + if err != nil { + select { + case <-s.closed: + return nil + case <-ctx.Done(): + return nil + default: + } + if errors.Is(err, net.ErrClosed) { + return nil + } + return err + } + if !s.admit(conn) { + continue + } + s.wait.Add(1) + go func(c net.Conn) { + defer s.wait.Done() + defer s.release(c) + s.serve(ctx, c) + }(conn) + } +} + +// ServeConn serves one already-accepted, already-classified plaintext +// connection — the shared-port handoff path. It blocks until the connection +// ends and reports whether it was admitted. +func (s *Server) ServeConn(ctx context.Context, conn net.Conn) bool { + select { + case <-s.closed: + _ = conn.Close() + return false + default: + } + if !s.admit(conn) { + return false + } + s.wait.Add(1) + defer s.wait.Done() + defer s.release(conn) + s.serve(ctx, conn) + return true +} + +// admit charges a connection against the max-connections cap. +func (s *Server) admit(conn net.Conn) bool { + s.stats.accepted.Add(1) + if s.sem != nil { + select { + case s.sem <- struct{}{}: + default: + s.stats.connectionsReject.Add(1) + _ = conn.Close() + return false + } + } + s.stats.activeConns.Add(1) + return true +} + +func (s *Server) release(conn net.Conn) { + if s.sem != nil { + <-s.sem + } + s.stats.activeConns.Add(-1) + _ = conn.Close() +} + +// serve runs the HCR frame loop on one connection. +func (s *Server) serve(ctx context.Context, conn net.Conn) { + remote := conn.RemoteAddr().String() + if tcpConn, ok := conn.(*net.TCPConn); ok { + _ = tcpConn.SetNoDelay(true) + } + hdrBuf := make([]byte, RequestHeaderSize) + + for { + // Leitura dos 62 bytes fixos do cabeçalho da requisição + if _, err := io.ReadFull(conn, hdrBuf); err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) { + return + } + s.logger.Warn("read_header_failed", "remote", remote, "err", err) + return + } + + req, err := UnmarshalRequestHeader(hdrBuf) + if err != nil { + s.stats.protocolErrors.Add(1) + s.logger.Warn("unmarshal_header_failed", + "remote", remote, + "err", err, + "code", hdrBuf[0], + "version", hdrBuf[1], + ) + return + } + + // Leitura do payload da requisição (se houver) + var payload []byte + if req.PayloadLen > 0 { + payload = make([]byte, req.PayloadLen) + if _, err := io.ReadFull(conn, payload); err != nil { + s.logger.Warn("read_payload_failed", "remote", remote, "err", err) + return + } + // Desmascara o payload recebido do cliente (Client -> Server: direction = 0) + maskPayload(payload, req.SessionID, req.Code, req.Sequence, DirRequest) + } + + s.logger.Debug("REQ", + "code", reqCodeNameShort(req.Code), + "remote", remote, + "seq", req.Sequence, + "len", req.PayloadLen, + "sess", shortID(req.SessionID), + ) + + // Despacho da requisição pelo código + closeClient := s.dispatchRequest(ctx, conn, req, payload) + if closeClient { + return + } + } +} + +// Close stops the server: no new sessions, all existing ones dropped. +func (s *Server) Close() { + s.closeOnce.Do(func() { + close(s.closed) + s.sessions.CloseAll() + }) +} + +// Wait blocks until every serving goroutine has returned. +func (s *Server) Wait() { s.wait.Wait() } + +// Stats returns a counter snapshot for the admin panel. +func (s *Server) Stats() StatsSnapshot { + return StatsSnapshot{ + StartedAt: s.started, + ActiveConnections: s.stats.activeConns.Load(), + ActiveSessions: s.sessions.Len(), + Accepted: s.stats.accepted.Load(), + ConnectionsRejected: s.stats.connectionsReject.Load(), + SessionsCreated: s.stats.sessionsCreated.Load(), + SessionsRejected: s.stats.sessionsRejected.Load(), + UploadBytes: s.stats.uploadBytes.Load(), + DownloadBytes: s.stats.downloadBytes.Load(), + ProtocolErrors: s.stats.protocolErrors.Load(), + } +} + +// dispatchRequest processa os códigos de operação 1..6 +func (s *Server) dispatchRequest(ctx context.Context, conn net.Conn, req *RequestHeader, payload []byte) bool { + remoteIP, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) + + switch req.Code { + case ReqConnect: // 1: Iniciar sessão + // Validações estritas do protocolo (de FUN_00663a00): + // - Sequence deve ser 0 + // - PayloadLen deve ser 0 + // - SessionID não pode ser nulo + var zeroID [16]byte + if req.Sequence != 0 || req.PayloadLen != 0 || req.SessionID == zeroID { + s.logger.Warn("connect_rejected_invalid", + "remote", remoteIP, + "seq", req.Sequence, + "payload_len", req.PayloadLen, + "is_zero_id", req.SessionID == zeroID, + ) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + + sess, err := s.sessions.CreateSession(req.SessionID, remoteIP) + if err != nil { + s.stats.sessionsRejected.Add(1) + s.logger.Error("connect_target_failed", "remote", remoteIP, "sess", shortID(req.SessionID), "err", err) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(err.Error())) + return false + } + s.stats.sessionsCreated.Add(1) + + s.logger.Info("connect_session_created", "remote", remoteIP, "sess", shortID(req.SessionID), "target", s.cfg.TargetAddr) + // Confirmação de conexão com token de 32 bytes de volta (SessionID + 16 zeros) + token := make([]byte, 32) + copy(token[:16], req.SessionID[:]) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, 0, token) + sess.touch() + return false + + case ReqData: // 2: Upload de dados para o alvo + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("data_session_not_found", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + if len(payload) == 0 { + s.logger.Warn("data_empty_payload", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + + sess.mu.Lock() + if sess.targetClosed { + sess.mu.Unlock() + s.logger.Warn("data_target_already_closed", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, []byte(ErrTargetBroken.Error())) + return false + } + + // Validação de sequence para upload (FUN_00661240 em hcr.c): + // Sequence de upload é o índice ordinal do pacote enviado pelo cliente (0, 1, 2...) + if req.Sequence < sess.writeSeq { + // Pacote duplicado já processado anteriormente (idempotente) + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + s.logger.Debug("data_duplicate_packet_ignored", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "write_seq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + } + + if req.Sequence > sess.writeSeq { + // Pacote fora de ordem + if req.Sequence-sess.writeSeq > 255 { + respSeq := sess.writeSeq + sess.mu.Unlock() + s.logger.Warn("data_seq_too_far_ahead", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "write_seq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, respSeq, []byte("SEQUENCE_INVALID")) + return false + } + if sess.upBuffer == nil { + sess.upBuffer = make(map[uint64][]byte) + } + bufCopy := make([]byte, len(payload)) + copy(bufCopy, payload) + sess.upBuffer[req.Sequence] = bufCopy + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + s.logger.Debug("data_buffered_out_of_order", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "waiting_for", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + } + + // req.Sequence == sess.writeSeq: agrupa pacotes contíguos e despacha para escrita assíncrona + sess.writeSeq++ + toWrite := payload + + // Descarrega quaisquer pacotes subsequentes contíguos que já estavam no upBuffer + for { + nextPayload, exists := sess.upBuffer[sess.writeSeq] + if !exists { + break + } + delete(sess.upBuffer, sess.writeSeq) + sess.writeSeq++ + toWrite = append(toWrite, nextPayload...) + } + + if !sess.targetClosed && sess.targetWriteCh != nil { + select { + case sess.targetWriteCh <- toWrite: + default: + go func(ch chan []byte, data []byte) { + ch <- data + }(sess.targetWriteCh, toWrite) + } + } + + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + + s.stats.uploadBytes.Add(uint64(len(payload))) + s.logger.Debug("DATA_OK", "sess", shortID(req.SessionID), "seq", req.Sequence, "bytes", len(payload), "newWriteSeq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + + case ReqPoll: // 3: Download / Polling de dados do alvo + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("poll_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + maxChunks := 1 + if len(payload) == 2 { + maxChunks = int(binary.BigEndian.Uint16(payload[:2])) + } else if len(payload) != 0 { + s.logger.Warn("poll_invalid_payload_len", "len", len(payload)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + if maxChunks <= 0 { + maxChunks = 1 + } + if maxChunks > 32 { + maxChunks = 32 + } + + maxFrame := s.cfg.MaxDownloadFrame + if maxFrame <= 0 || maxFrame > 16384 { + maxFrame = 16384 + } + + sess.mu.Lock() + sess.touch() + + // Validação de ACK no hcr.c (FUN_0065d4c0 / linha 341072 e 345332): + // Se já houve ACK e req.Sequence <= ackSeq: não é erro fatal, retorna StatusPollTimeout (2) + if sess.hasAcked && req.Sequence <= sess.ackSeq { + sess.mu.Unlock() + s.logger.Debug("poll_already_acked", "sess", shortID(req.SessionID), "req_seq", req.Sequence, "ack_seq", sess.ackSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollTimeout, req.Sequence, nil) + return false + } + + // Se o worker está adiantado em relação à esteira contígua (> 255 frames à frente): + // Retorna StatusPollTimeout (2) para que o worker reconsulte sem abortar o túnel + if req.Sequence > sess.deliveredSeq && req.Sequence-sess.deliveredSeq > 255 { + sess.mu.Unlock() + s.logger.Debug("poll_seq_ahead_timeout", "sess", shortID(req.SessionID), "req_seq", req.Sequence, "delivered_seq", sess.deliveredSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollTimeout, req.Sequence, nil) + return false + } + + // Long-polling sequencial estrito (hcr.c linha 341103): + // Enquanto req.Sequence > deliveredSeq (worker adiantado em relação à esteira contígua) + // ou não há frames disponíveis a partir de req.Sequence, aguarda notificação em broadcast + pollTimer := time.NewTimer(s.cfg.DownloadPollTimeout) + defer pollTimer.Stop() + + for (req.Sequence > sess.deliveredSeq || !sess.hasFramesFrom(req.Sequence)) && !sess.targetClosed { + notifyCh := sess.dataNotify + sess.mu.Unlock() + select { + case <-pollTimer.C: + sess.mu.Lock() + goto finishPoll + case <-notifyCh: + sess.mu.Lock() + case <-ctx.Done(): + sess.mu.Lock() + goto finishPoll + } + } + + finishPoll: + var matching []*DownloadFrame + if req.Sequence <= sess.deliveredSeq { + matching = sess.getFramesFrom(req.Sequence, maxChunks, int(MaxPayloadLimit)) + } + + if len(matching) == 0 { + status := StatusPollTimeout // 2: Timeout / sem dados no intervalo (FUN_00664300 linha 345408) + if sess.targetClosed { + status = StatusClosed // 3: Conexão com o alvo encerrou + } + sess.mu.Unlock() + s.writeResponse(conn, req.SessionID, req.Code, status, req.Sequence, nil) + return false + } + + // Cada chunk no payload retornado deve ser precedido por seu tamanho uint32 BigEndian + var framed []byte + var highestSeq uint64 + for _, f := range matching { + chunkHdr := make([]byte, 4) + binary.BigEndian.PutUint32(chunkHdr, uint32(len(f.Data))) + framed = append(framed, chunkHdr...) + framed = append(framed, f.Data...) + highestSeq = f.Seq + } + if highestSeq+1 > sess.deliveredSeq { + sess.deliveredSeq = highestSeq + 1 + } + sess.notifyDataLocked() + sess.touch() + sess.mu.Unlock() + + s.logger.Debug("POLL_DATA", + "sess", shortID(req.SessionID), + "chunks", len(matching), + "bytes", len(framed), + "req_seq", req.Sequence, + "delivered_seq", sess.deliveredSeq, + ) + s.stats.downloadBytes.Add(uint64(len(framed))) + // Conforme FUN_00664300 em hcr.c (linha 345282), resposta com dados usa StatusPollData (1) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollData, req.Sequence, framed) + return false + + case ReqAck: // 4: Confirmação de recebimento (ACK) + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("ack_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + sess.mu.Lock() + var remaining []*DownloadFrame + var ackedBytes int + for _, f := range sess.downBuffer { + if f.Seq <= req.Sequence { + ackedBytes += len(f.Data) + } else { + remaining = append(remaining, f) + } + } + sess.downBuffer = remaining + sess.pendingBytes -= ackedBytes + if sess.pendingBytes < 0 { + sess.pendingBytes = 0 + } + sess.ackSeq = req.Sequence + sess.hasAcked = true + sess.notifyDataLocked() + sess.touch() + sess.mu.Unlock() + + s.logger.Debug("ACK_OK", "sess", shortID(req.SessionID), "seq", req.Sequence, "freed", ackedBytes, "pending", sess.pendingBytes) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, req.Sequence, nil) + return false + + case ReqClose: // 5: Fechar sessão + s.logger.Info("session_closed_by_request", "sess", shortID(req.SessionID)) + s.sessions.CloseSession(req.SessionID) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + return true + + case ReqPing: // 6: Keepalive / Ping + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("ping_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + return true + } + sess.mu.Lock() + closed := sess.targetClosed + sess.touch() + sess.mu.Unlock() + if closed { + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + } else { + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, req.Sequence, nil) + } + return false + + default: + s.logger.Warn("unknown_request_code", "code", req.Code, "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return true + } +} + +// writeResponse envia os 14 bytes do ResponseHeader seguidos do payload mascarado +func (s *Server) writeResponse(conn net.Conn, sessionID [16]byte, code uint8, status uint8, seq uint64, payload []byte) { + pLen := uint32(len(payload)) + hdr := MarshalResponseHeader(status, seq, pLen) + + s.logger.Debug("RESP", + "code", reqCodeNameShort(code), + "status", statusCodeNameShort(status), + "seq", seq, + "len", pLen, + ) + + if len(payload) == 0 { + conn.Write(hdr) + return + } + + // Mascara o payload de saída (Server -> Client: direction = 1) + outPayload := make([]byte, len(payload)) + copy(outPayload, payload) + maskPayload(outPayload, sessionID, code, seq, DirResponse) + + buf := append(hdr, outPayload...) + conn.Write(buf) +} + +func (s *Server) idleReaperLoop(ctx context.Context) { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + reaped := s.sessions.ReapIdleSessions() + if reaped > 0 { + s.logger.Info("idle_sessions_reaped", "count", reaped) + } + } + } +} diff --git a/internal/hcr/sniff.go b/internal/hcr/sniff.go new file mode 100644 index 0000000..f206f5b --- /dev/null +++ b/internal/hcr/sniff.go @@ -0,0 +1,84 @@ +package hcr + +import "encoding/binary" + +// Verdict is the result of inspecting the first bytes of a connection. +type Verdict int + +const ( + // VerdictNo means the bytes cannot begin an HCR request. + VerdictNo Verdict = iota + // VerdictMore means the bytes so far are consistent with HCR but more are + // needed to decide. The caller should peek further and ask again. + VerdictMore + // VerdictYes means the bytes begin a valid HCR request header. + VerdictYes +) + +// SniffLimit is the largest number of bytes SniffFrame ever needs: the full +// fixed request header. +const SniffLimit = RequestHeaderSize + +// IsHeader reports whether buf is a complete, valid 62-byte HCR request header. +// This is the strict check the coexistence design relies on: only a full header +// with the fixed protocol version and an in-range payload length counts. +func IsHeader(buf []byte) bool { + if len(buf) < RequestHeaderSize { + return false + } + code := buf[0] + if code < 1 || code > 6 { + return false + } + if buf[1] != ProtoVersion { + return false + } + if binary.BigEndian.Uint32(buf[58:62]) > MaxPayloadLimit { + return false + } + return true +} + +// SniffFrame reports whether data begins an HCR request, so a port shared with +// BHTTP (and SSH, HTTP injection) can route the connection without consuming +// anything. +// +// HCR and BHTTP deliberately overlap on the first byte (opcodes 1..4 mean +// upload/download/… in both). The discriminator is HCR's fixed protocol version +// at byte [1] (always 0x01) and its 62-byte header layout, checked in full: +// +// - byte 0 must be an HCR opcode (1..6); anything else (including BHTTP's +// probe 0x00) is not HCR. +// - byte 1 must be 0x01. A BHTTP frame's byte [1] is the first byte of its +// random session UUID, so it is 0x01 only by chance — and that is the only +// case where HCR waits for the full 62 bytes. A "clean" BHTTP frame is +// rejected here at two bytes, with no stall, and falls through to BHTTP. +// - the full 62-byte header must pass IsHeader. A BHTTP frame whose UUID +// happens to start 0x01 almost never has a valid HCR payload length at +// [58:62], so it is rejected and BHTTP still handles it. +// +// The caller must try HCR before BHTTP, exactly because a real HCR Connect +// (opcode 1) also looks like a BHTTP upload on the first byte. +func SniffFrame(data []byte) Verdict { + if len(data) == 0 { + return VerdictMore + } + if data[0] < 1 || data[0] > 6 { + return VerdictNo + } + if len(data) < 2 { + return VerdictMore + } + if data[1] != ProtoVersion { + // Not HCR: a BHTTP frame or junk. Reject now so BHTTP gets its fast + // 29-byte path with no wait for 62 bytes. + return VerdictNo + } + if len(data) < RequestHeaderSize { + return VerdictMore + } + if IsHeader(data[:RequestHeaderSize]) { + return VerdictYes + } + return VerdictNo +} diff --git a/internal/hcr/sniff_test.go b/internal/hcr/sniff_test.go new file mode 100644 index 0000000..63f77bc --- /dev/null +++ b/internal/hcr/sniff_test.go @@ -0,0 +1,83 @@ +package hcr + +import ( + "encoding/binary" + "testing" +) + +// hcrHeader builds a valid 62-byte request header. +func hcrHeader(code, version byte, payloadLen uint32) []byte { + b := make([]byte, RequestHeaderSize) + b[0] = code + b[1] = version + b[2] = 0xAB // session id byte + binary.BigEndian.PutUint32(b[58:62], payloadLen) + return b +} + +func TestSniffRejectsOtherProtocols(t *testing.T) { + cases := map[string]string{ + "SSH": "SSH-2.0-x\r\n", + "HTTP GET": "GET / HTTP/1.1\r\n", + "BTUN": "DTUNNEL/1.1 CLIENT_HELLO\r\n", + "BHTTP probe": "\x00\x11\x22\x33", + "TLS hello": "\x16\x03\x01\x00", + } + for name, in := range cases { + if got := SniffFrame([]byte(in)); got != VerdictNo { + t.Fatalf("%s: SniffFrame = %v, want VerdictNo", name, got) + } + } +} + +func TestSniffAcceptsValidHeaders(t *testing.T) { + for code := byte(1); code <= 6; code++ { + if got := SniffFrame(hcrHeader(code, ProtoVersion, 100)); got != VerdictYes { + t.Fatalf("code %d: SniffFrame = %v, want VerdictYes", code, got) + } + } +} + +// A BHTTP frame whose session UUID happens to start 0x01 must NOT be stolen: +// its bytes at [58:62] are not a valid HCR payload length. +func TestSniffRejectsBhttpLookalike(t *testing.T) { + b := make([]byte, RequestHeaderSize) + b[0] = 0x01 // BHTTP upload / HCR connect + b[1] = 0x01 // UUID happens to start 0x01 + binary.BigEndian.PutUint32(b[58:62], MaxPayloadLimit+1) // invalid HCR len + if got := SniffFrame(b); got != VerdictNo { + t.Fatalf("lookalike: SniffFrame = %v, want VerdictNo", got) + } +} + +// A clean BHTTP frame (byte1 != 0x01) is rejected at two bytes — no 62-byte wait. +func TestSniffFastRejectsCleanBhttp(t *testing.T) { + if got := SniffFrame([]byte{0x01, 0x7A}); got != VerdictNo { + t.Fatalf("clean BHTTP: SniffFrame(2B) = %v, want VerdictNo", got) + } +} + +func TestSniffProgressive(t *testing.T) { + full := hcrHeader(1, ProtoVersion, 10) + if got := SniffFrame(nil); got != VerdictMore { + t.Fatalf("empty = %v, want More", got) + } + if got := SniffFrame(full[:1]); got != VerdictMore { + t.Fatalf("1 byte = %v, want More", got) + } + if got := SniffFrame(full[:2]); got != VerdictMore { + t.Fatalf("2 bytes (ver=1) = %v, want More", got) + } + if got := SniffFrame(full[:RequestHeaderSize-1]); got != VerdictMore { + t.Fatalf("61 bytes = %v, want More", got) + } + if got := SniffFrame(full); got != VerdictYes { + t.Fatalf("full = %v, want Yes", got) + } +} + +func TestSniffRejectsWrongVersion(t *testing.T) { + if got := SniffFrame(hcrHeader(1, 0x02, 10)); got != VerdictNo { + t.Fatalf("version 2 = %v, want No", got) + } +} diff --git a/internal/turbotunnel/clientid.go b/internal/turbotunnel/clientid.go new file mode 100644 index 0000000..06ff837 --- /dev/null +++ b/internal/turbotunnel/clientid.go @@ -0,0 +1,37 @@ +// This package is a local fork of www.bamsoftware.com/git/dnstt.git/turbotunnel +// (upstream v1.20241021.0). The only behavioural change from upstream is that +// RemoteMap's background expiry goroutine is now stoppable via Close(), wired +// through QueuePacketConn.Close(); see remotemap.go and queuepacketconn.go. +// Upstream leaks that goroutine for the process lifetime, which is harmless for +// the upstream one-shot server but leaks one goroutine per DNSTT restart in this +// integration (hot-reload / auto-restart). clientid.go and consts.go are copied +// verbatim. + +package turbotunnel + +import ( + "crypto/rand" + "encoding/hex" +) + +// ClientID is an abstract identifier that binds together all the communications +// belonging to a single client session, even though those communications may +// arrive from multiple IP addresses or over multiple lower-level connections. +// It plays the same role that an (IP address, port number) tuple plays in a +// net.UDPConn: it's the return address pertaining to a long-lived abstract +// client session. The client attaches its ClientID to each of its +// communications, enabling the server to disambiguate requests among its many +// clients. ClientID implements the net.Addr interface. +type ClientID [8]byte + +func NewClientID() ClientID { + var id ClientID + _, err := rand.Read(id[:]) + if err != nil { + panic(err) + } + return id +} + +func (id ClientID) Network() string { return "clientid" } +func (id ClientID) String() string { return hex.EncodeToString(id[:]) } diff --git a/internal/turbotunnel/consts.go b/internal/turbotunnel/consts.go new file mode 100644 index 0000000..5684bf7 --- /dev/null +++ b/internal/turbotunnel/consts.go @@ -0,0 +1,22 @@ +// Package turbotunnel is facilities for embedding packet-based reliability +// protocols inside other protocols. +// +// https://github.com/net4people/bbs/issues/9 +package turbotunnel + +import "errors" + +// QueueSize is the size of send and receive queues in QueuePacketConn and +// RemoteMap. +const QueueSize = 128 + +var errClosedPacketConn = errors.New("operation on closed connection") +var errNotImplemented = errors.New("not implemented") + +// DummyAddr is a placeholder net.Addr, for when a programming interface +// requires a net.Addr but there is none relevant. All DummyAddrs compare equal +// to each other. +type DummyAddr struct{} + +func (addr DummyAddr) Network() string { return "dummy" } +func (addr DummyAddr) String() string { return "dummy" } diff --git a/internal/turbotunnel/queuepacketconn.go b/internal/turbotunnel/queuepacketconn.go new file mode 100644 index 0000000..2097cca --- /dev/null +++ b/internal/turbotunnel/queuepacketconn.go @@ -0,0 +1,165 @@ +package turbotunnel + +import ( + "net" + "sync" + "sync/atomic" + "time" +) + +// taggedPacket is a combination of a []byte and a net.Addr, encapsulating the +// return type of PacketConn.ReadFrom. +type taggedPacket struct { + P []byte + Addr net.Addr +} + +// QueuePacketConn implements net.PacketConn by storing queues of packets. There +// is one incoming queue (where packets are additionally tagged by the source +// address of the peer that sent them). There are many outgoing queues, one for +// each remote peer address that has been recently seen. The QueueIncoming +// method inserts a packet into the incoming queue, to eventually be returned by +// ReadFrom. WriteTo inserts a packet into an address-specific outgoing queue, +// which can later by accessed through the OutgoingQueue method. +// +// Besides the outgoing queues, there is also a one-element "stash" for each +// remote peer address. You can stash a packet using the Stash method, and get +// it back later by receiving from the channel returned by Unstash. The stash is +// meant as a convenient place to temporarily store a single packet, such as +// when you've read one too many packets from the send queue and need to store +// the extra packet to be processed first in the next pass. It's the caller's +// responsibility to Unstash what they have Stashed. Calling Stash does not put +// the packet at the head of the send queue; if there is the possibility that a +// packet has been stashed, it must be checked for by calling Unstash in +// addition to OutgoingQueue. +type QueuePacketConn struct { + remotes *RemoteMap + localAddr net.Addr + recvQueue chan taggedPacket + closeOnce sync.Once + closed chan struct{} + // What error to return when the QueuePacketConn is closed. + err atomic.Value +} + +// NewQueuePacketConn makes a new QueuePacketConn, set to track recent peers +// for at least a duration of timeout. +func NewQueuePacketConn(localAddr net.Addr, timeout time.Duration) *QueuePacketConn { + return &QueuePacketConn{ + remotes: NewRemoteMap(timeout), + localAddr: localAddr, + recvQueue: make(chan taggedPacket, QueueSize), + closed: make(chan struct{}), + } +} + +// QueueIncoming queues and incoming packet and its source address, to be +// returned in a future call to ReadFrom. +func (c *QueuePacketConn) QueueIncoming(p []byte, addr net.Addr) { + select { + case <-c.closed: + // If we're closed, silently drop it. + return + default: + } + // Copy the slice so that the caller may reuse it. + buf := make([]byte, len(p)) + copy(buf, p) + select { + case c.recvQueue <- taggedPacket{buf, addr}: + default: + // Drop the incoming packet if the receive queue is full. + } +} + +// OutgoingQueue returns the queue of outgoing packets corresponding to addr, +// creating it if necessary. The contents of the queue will be packets that are +// written to the address in question using WriteTo. +func (c *QueuePacketConn) OutgoingQueue(addr net.Addr) <-chan []byte { + return c.remotes.SendQueue(addr) +} + +// Stash places p in the stash for addr, if the stash is not already occupied. +// Returns true if the packet was placed in the stash, or false if the stash was +// already occupied. This method is similar to WriteTo, except that it puts the +// packet in the stash queue (accessible via Unstash), rather than the outgoing +// queue (accessible via OutgoingQueue). +func (c *QueuePacketConn) Stash(p []byte, addr net.Addr) bool { + return c.remotes.Stash(addr, p) +} + +// Unstash returns the channel that represents the stash for addr. +func (c *QueuePacketConn) Unstash(addr net.Addr) <-chan []byte { + return c.remotes.Unstash(addr) +} + +// ReadFrom returns a packet and address previously stored by QueueIncoming. +func (c *QueuePacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + select { + case <-c.closed: + return 0, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)} + default: + } + select { + case <-c.closed: + return 0, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)} + case packet := <-c.recvQueue: + return copy(p, packet.P), packet.Addr, nil + } +} + +// WriteTo queues an outgoing packet for the given address. The queue can later +// be retrieved using the OutgoingQueue method. +func (c *QueuePacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { + select { + case <-c.closed: + return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)} + default: + } + // Copy the slice so that the caller may reuse it. + buf := make([]byte, len(p)) + copy(buf, p) + select { + case c.remotes.SendQueue(addr) <- buf: + return len(buf), nil + default: + // Drop the outgoing packet if the send queue is full. + return len(buf), nil + } +} + +// closeWithError unblocks pending operations and makes future operations fail +// with the given error. If err is nil, it becomes errClosedPacketConn. +func (c *QueuePacketConn) closeWithError(err error) error { + var newlyClosed bool + c.closeOnce.Do(func() { + newlyClosed = true + // Store the error to be returned by future PacketConn + // operations. + if err == nil { + err = errClosedPacketConn + } + c.err.Store(err) + close(c.closed) + // LOCAL FORK ADDITION: stop the RemoteMap expiry goroutine so it is not + // leaked for the process lifetime. Upstream never does this. + c.remotes.Close() + }) + if !newlyClosed { + return &net.OpError{Op: "close", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)} + } + return nil +} + +// Close unblocks pending operations and makes future operations fail with a +// "closed connection" error. +func (c *QueuePacketConn) Close() error { + return c.closeWithError(nil) +} + +// LocalAddr returns the localAddr value that was passed to NewQueuePacketConn. +func (c *QueuePacketConn) LocalAddr() net.Addr { return c.localAddr } + +func (c *QueuePacketConn) SetDeadline(t time.Time) error { return errNotImplemented } +func (c *QueuePacketConn) SetReadDeadline(t time.Time) error { return errNotImplemented } +func (c *QueuePacketConn) SetWriteDeadline(t time.Time) error { return errNotImplemented } diff --git a/internal/turbotunnel/remotemap.go b/internal/turbotunnel/remotemap.go new file mode 100644 index 0000000..fecea3f --- /dev/null +++ b/internal/turbotunnel/remotemap.go @@ -0,0 +1,198 @@ +package turbotunnel + +import ( + "container/heap" + "net" + "sync" + "time" +) + +// remoteRecord is a record of a recently seen remote peer, with the time it was +// last seen and queues of outgoing packets. +type remoteRecord struct { + Addr net.Addr + LastSeen time.Time + SendQueue chan []byte + Stash chan []byte +} + +// RemoteMap manages a mapping of live remote peers, keyed by address, to their +// respective send queues. Each peer has two queues: a primary send queue, and a +// "stash". The primary send queue is returned by the SendQueue method. The +// stash is an auxiliary one-element queue accessed using the Stash and Unstash +// methods. The stash is meant for use by callers that need to "unread" a packet +// that's already been removed from the primary send queue. +// +// RemoteMap's functions are safe to call from multiple goroutines. +type RemoteMap struct { + // We use an inner structure to avoid exposing public heap.Interface + // functions to users of remoteMap. + inner remoteMapInner + // Synchronizes access to inner. + lock sync.Mutex + // closed stops the background expiry goroutine. LOCAL FORK ADDITION: + // upstream has no way to stop that goroutine, which leaks it for the + // process lifetime on every RemoteMap created. + closed chan struct{} + closeOnce sync.Once +} + +// NewRemoteMap creates a RemoteMap that expires peers after a timeout. +// +// If the timeout is 0, peers never expire. +// +// The timeout does not have to be kept in sync with smux's idle timeout. If a +// peer is removed from the map while the smux session is still live, the worst +// that can happen is a loss of whatever packets were in the send queue at the +// time. If smux later decides to send more packets to the same peer, we'll +// instantiate a new send queue, and if the peer is ever seen again with a +// matching address, we'll deliver them. +func NewRemoteMap(timeout time.Duration) *RemoteMap { + m := &RemoteMap{ + inner: remoteMapInner{ + byAge: make([]*remoteRecord, 0), + byAddr: make(map[net.Addr]int), + }, + closed: make(chan struct{}), + } + if timeout > 0 { + // LOCAL FORK CHANGE: upstream is `for { time.Sleep(timeout/2); ... }` + // with no exit. Use a ticker and select on m.closed so Close() can stop + // this goroutine. + go func() { + ticker := time.NewTicker(timeout / 2) + defer ticker.Stop() + for { + select { + case <-m.closed: + return + case now := <-ticker.C: + m.lock.Lock() + m.inner.removeExpired(now, timeout) + m.lock.Unlock() + } + } + }() + } + return m +} + +// Close stops the background expiry goroutine started by NewRemoteMap. It is +// safe to call more than once. LOCAL FORK ADDITION. +func (m *RemoteMap) Close() error { + m.closeOnce.Do(func() { close(m.closed) }) + return nil +} + +// SendQueue returns the send queue corresponding to addr, creating it if +// necessary. +func (m *RemoteMap) SendQueue(addr net.Addr) chan []byte { + m.lock.Lock() + defer m.lock.Unlock() + return m.inner.Lookup(addr, time.Now()).SendQueue +} + +// Stash places p in the stash corresponding to addr, if the stash is not +// already occupied. Returns true if the p was placed in the stash, false +// otherwise. +func (m *RemoteMap) Stash(addr net.Addr, p []byte) bool { + m.lock.Lock() + defer m.lock.Unlock() + select { + case m.inner.Lookup(addr, time.Now()).Stash <- p: + return true + default: + return false + } +} + +// Unstash returns the channel that reads from the stash for addr. +func (m *RemoteMap) Unstash(addr net.Addr) <-chan []byte { + m.lock.Lock() + defer m.lock.Unlock() + return m.inner.Lookup(addr, time.Now()).Stash +} + +// remoteMapInner is the inner type of RemoteMap, implementing heap.Interface. +// byAge is the backing store, a heap ordered by LastSeen time, to facilitate +// expiring old records. byAddr is a map from addresses to heap indices, to +// allow looking up by address. Unlike RemoteMap, remoteMapInner requires +// external synchonization. +type remoteMapInner struct { + byAge []*remoteRecord + byAddr map[net.Addr]int +} + +// removeExpired removes all records whose LastSeen timestamp is more than +// timeout in the past. +func (inner *remoteMapInner) removeExpired(now time.Time, timeout time.Duration) { + for len(inner.byAge) > 0 && now.Sub(inner.byAge[0].LastSeen) >= timeout { + record := heap.Pop(inner).(*remoteRecord) + close(record.SendQueue) + } +} + +// Lookup finds the existing record corresponding to addr, or creates a new +// one if none exists yet. It updates the record's LastSeen time and returns the +// record. +func (inner *remoteMapInner) Lookup(addr net.Addr, now time.Time) *remoteRecord { + var record *remoteRecord + i, ok := inner.byAddr[addr] + if ok { + // Found one, update its LastSeen. + record = inner.byAge[i] + record.LastSeen = now + heap.Fix(inner, i) + } else { + // Not found, create a new one. + record = &remoteRecord{ + Addr: addr, + LastSeen: now, + SendQueue: make(chan []byte, QueueSize), + Stash: make(chan []byte, 1), + } + heap.Push(inner, record) + } + return record +} + +// heap.Interface for remoteMapInner. + +func (inner *remoteMapInner) Len() int { + if len(inner.byAge) != len(inner.byAddr) { + panic("inconsistent remoteMap") + } + return len(inner.byAge) +} + +func (inner *remoteMapInner) Less(i, j int) bool { + return inner.byAge[i].LastSeen.Before(inner.byAge[j].LastSeen) +} + +func (inner *remoteMapInner) Swap(i, j int) { + inner.byAge[i], inner.byAge[j] = inner.byAge[j], inner.byAge[i] + inner.byAddr[inner.byAge[i].Addr] = i + inner.byAddr[inner.byAge[j].Addr] = j +} + +func (inner *remoteMapInner) Push(x interface{}) { + record := x.(*remoteRecord) + if _, ok := inner.byAddr[record.Addr]; ok { + panic("duplicate address in remoteMap") + } + // Insert into byAddr map. + inner.byAddr[record.Addr] = len(inner.byAge) + // Insert into byAge slice. + inner.byAge = append(inner.byAge, record) +} + +func (inner *remoteMapInner) Pop() interface{} { + n := len(inner.byAddr) + // Remove from byAge slice. + record := inner.byAge[n-1] + inner.byAge[n-1] = nil + inner.byAge = inner.byAge[:n-1] + // Remove from byAddr map. + delete(inner.byAddr, record.Addr) + return record +} diff --git a/internal/turbotunnel/remotemap_leak_test.go b/internal/turbotunnel/remotemap_leak_test.go new file mode 100644 index 0000000..78a470c --- /dev/null +++ b/internal/turbotunnel/remotemap_leak_test.go @@ -0,0 +1,51 @@ +package turbotunnel + +import ( + "runtime" + "testing" + "time" +) + +// TestQueuePacketConnCloseStopsGoroutine is the regression test for the local +// fork's reason to exist: upstream's RemoteMap expiry goroutine runs forever, +// so creating and discarding many QueuePacketConns (as DNSTT restart does) +// leaks one goroutine each. After Close(), the count must return to baseline. +func TestQueuePacketConnCloseStopsGoroutine(t *testing.T) { + // Let any goroutines from earlier settle. + settle := func() { + for i := 0; i < 50; i++ { + runtime.GC() + time.Sleep(2 * time.Millisecond) + } + } + settle() + base := runtime.NumGoroutine() + + const n = 200 + for i := 0; i < n; i++ { + // Short timeout so the goroutine is definitely started (timeout > 0). + c := NewQueuePacketConn(DummyAddr{}, 50*time.Millisecond) + if err := c.Close(); err != nil { + t.Fatalf("Close returned error: %v", err) + } + } + settle() + + got := runtime.NumGoroutine() + // Allow a small slack for scheduler/runtime goroutines; the key point is we + // are nowhere near base+n (which is what the upstream leak would produce). + if got > base+20 { + t.Fatalf("goroutine leak: baseline=%d after %d create/close cycles=%d (want <= baseline+20)", base, n, got) + } +} + +// TestRemoteMapCloseIdempotent verifies Close can be called repeatedly. +func TestRemoteMapCloseIdempotent(t *testing.T) { + m := NewRemoteMap(10 * time.Millisecond) + if err := m.Close(); err != nil { + t.Fatalf("first Close: %v", err) + } + if err := m.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..d74cf84 --- /dev/null +++ b/main.go @@ -0,0 +1,3686 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "crypto/hmac" + "crypto/sha1" + "crypto/tls" + "database/sql" + "encoding/base32" + "encoding/binary" + "encoding/json" + "flag" + "fmt" + "io" + "log" + "net" + "net/http" + "net/url" + "os" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + _ "github.com/lib/pq" + "golang.org/x/crypto/ssh" + "golang.org/x/time/rate" + "runtime/debug" +) + +const ( + // Hard timeouts to ensure half-open connections don't leak goroutines. + // This also bounds DNSTT SSH handshakes (streamConn now honors deadlines), + // which travel over DNS and need more headroom than a direct TCP handshake; + // 45s is generous for slow/lossy DNS paths while still reaping wedged streams. + sshHandshakeTimeout = 45 * time.Second + tlsHandshakeTimeout = 15 * time.Second + // Dial timeout for direct-tcpip backend connections. + directTCPIPDialTimeout = 10 * time.Second + // VPN transports must remain connected even when the user is temporarily + // idle. Dead peers are released by transport errors/request cancellation, + // not by a short application-level inactivity timer. Operators may still + // set ssh_idle_timeout explicitly when they intentionally want one. + defaultSSHIdleTimeout time.Duration = 0 +) + +// ---------- Config types ---------- + +// TLSForwarderConfig specifies a TLS listener that accepts encrypted +// connections and passes the decrypted stream directly into the SSH +// handler. The listener binds to the given address (which should be +// specified in bracket form for IPv6, e.g. "[2001:db8::1]:443") and +// terminates TLS using the provided certificate and key files. Each +// connection is then handled by the same handleConn logic as the +// plain TCP listeners. If no TLS forwarders are configured, no +// TLS listeners are started. +type TLSForwarderConfig struct { + // Listen address for the TLS‑wrapped SSH service. For IPv6, use + // bracket form, e.g. "[2001:db8::10]:443" or "[::]:443". + Listen string `json:"listen"` + // CertFile is the path to the TLS certificate in PEM format. + CertFile string `json:"cert_file"` + // KeyFile is the path to the corresponding private key in PEM format. + KeyFile string `json:"key_file"` +} + +type Config struct { + Listen string `json:"listen"` + + // ProxyAutoRestartInterval controls a watchdog that periodically hard-restarts + // the public proxy listeners (listen, extra_listen, and TLS forwarders) and + // closes active SSH sessions. Empty, "0s", "off", or "disabled" turns it off. + // Valid examples: "30m", "6h", "24h". Minimum accepted value is 1m. + ProxyAutoRestartInterval string `json:"proxy_auto_restart_interval,omitempty"` + + // ProxyAutoRestartGrace is the delay between closing proxy listeners/sessions + // and binding them again during an auto restart. Empty defaults to "2s". + ProxyAutoRestartGrace string `json:"proxy_auto_restart_grace,omitempty"` + + // Optional extra public listen addresses (multi‑port). These + // addresses use the same HTTP‑cleanup and SSH handler as the + // primary Listen address. For IPv6, use bracket form, e.g. + // "[::]:80", "[2001:db8::20]:8080". Empty slice means no + // additional listeners. + ExtraListen []string `json:"extra_listen"` + // LocalSSHListen is the raw SSH endpoint used by local proxy/tunnel daemons. + // It is always enabled, defaults to 127.0.0.1:2222, and is restricted to a + // numeric loopback address so it cannot accidentally become a public port. + LocalSSHListen string `json:"local_ssh_listen"` + HostKeyFile string `json:"host_key_file"` + Quiet bool `json:"quiet"` + + Banner string `json:"banner"` + BannerFile string `json:"banner_file"` + + UserCount bool `json:"user_count"` + + // PAMAuthEnabled turns on Linux system-password login for this server. When + // true, an SSH login with a username not present in the panel is verified + // against /etc/shadow; on success the account (regular users, UID >= 1000) + // is auto-imported into the panel. When false, only panel-managed accounts + // can log in and previously-imported PAM accounts are refused. + PAMAuthEnabled bool `json:"pam_auth_enabled"` + + // SSHIdleTimeout controls how long an authenticated SSH connection may + // remain with no bytes moving in either direction before it is closed and + // released from the active user count. Empty, "0", or "0s" disables it. + // VPN/XHTTP connections should normally leave this disabled. + SSHIdleTimeout string `json:"ssh_idle_timeout,omitempty"` + + // MaxTotalConnections caps the total number of concurrent SSH connections + // across all users. Once reached, new connections are rejected before the + // (expensive) SSH handshake, so a surge past normal load cannot exhaust + // memory/CPU and crash the server. 0 or empty uses the default (10000); + // set to -1 to disable the global cap entirely. + MaxTotalConnections int `json:"max_total_connections,omitempty"` + + // Default per-connection bandwidth limits (if user-specific = 0) + DefaultLimitMbpsUp int `json:"default_limit_mbps_up"` + DefaultLimitMbpsDown int `json:"default_limit_mbps_down"` + + Users []UserConfig `json:"users"` + + // DNSTT holds configuration for the DNS tunnel server. If nil, the DNS + // tunnel server is disabled. Domain is the DNS zone used for tunnelled + // queries (e.g. "t.example.com"). UDPListen specifies the UDP address + // to listen on (IPv6 syntax like "[::]:5300"). PrivKeyFile points to + // the private key used for the Noise handshake between client and server. + DNSTT *DNSTTConfig `json:"dnstt"` + + // UDPGW holds configuration for the integrated UDP gateway. If nil, the + // gateway is disabled. The gateway implements the BadVPN udpgw protocol + // (connID + X + IPv4 + port framing) and forwards UDP datagrams between a + // TCP client and arbitrary destinations. See udpgwstandalone.go for + // implementation details. + UDPGW *UDPGWConfig `json:"udpgw"` + + // Optional TLS listeners (stunnel‑like): accept TLS and handle SSH on + // the same process (no TCP backend). Each forwarder binds to the + // given address and terminates TLS using the specified certificate + // and key. If no TLS forwarders are defined, the server does not + // listen for TLS connections. See serveTLSSSH for implementation. + TLSForwarders []TLSForwarderConfig `json:"tls_forwarders"` + + // Xray holds configuration for the integrated Xray-core process. If nil + // the Xray subprocess is not started. See xray_integration.go. + Xray *XrayConfig `json:"xray"` + + // BHTTP holds configuration for the integrated BHTTP (BHP1/BHP2) transport. + // If nil, the transport is disabled. Sessions are relayed to this process's + // own SSH server, never to the system sshd. See bhttp_integration.go. + BHTTP *BHTTPConfig `json:"bhttp"` + + // BTUN holds configuration for the integrated BTUN protocol server. If nil, + // the server is disabled. BTUN moves IP packets rather than an SSH stream, + // so it authenticates against the panel's own account database — never PAM + // or /etc/shadow. See btun_integration.go. + BTUN *BTUNConfig `json:"btun"` + + // HCR holds configuration for the integrated HCR (HTTP/Custom Relay) + // transport. If nil, it is disabled. Like BHTTP, each session is relayed to + // this process's own SSH server, and it can coexist with BHTTP on the same + // ports. See hcr_integration.go. + HCR *HCRConfig `json:"hcr"` +} + +// DNSTTConfig defines the settings for the integrated dnstt server. See +// https://www.bamsoftware.com/software/dnstt/ for background on dnstt. The +// server listens on the UDP address in UDPListen, uses Domain as the root of +// the tunnelled zone, and loads its private key from PrivKeyFile. The +// corresponding public key must be distributed to clients. +type DNSTTConfig struct { + // Domain is the primary/root DNS zone reserved for the tunnel (e.g. "t.example.com"). + // It is kept for backward compatibility and is also used as the first client + // domain when Domains is empty. + Domain string `json:"domain"` + + // Domains optionally lists all DNS root zones/NS domains accepted by this + // server. This allows the same DNSTT listener/key to answer for public and + // local DNS deployments at the same time, for example: + // ["t.example.com", "t.local.lan"]. The first normalized value is mirrored + // into Domain for older clients/UI code. + Domains []string `json:"domains,omitempty"` + // UDPListen is the UDP address to listen on for incoming DNS tunnel queries. + // IPv6 addresses must use bracket form, for example "[::]:5300" or + // "[2001:db8::1234]:53". IPv6 listeners are opened with udp6 so they do + // not require a spare IPv4 address on the same port. + UDPListen string `json:"udp_listen"` + + // FakeDNSEnabled starts an extra built-in DNS listener for local/LAN testing. + // It uses the same DNSTT private key and session pool, but only accepts the + // FakeDNSDomain zone. This avoids needing a second DNS server for tests such + // as t.local.lan over a dedicated IPv6 address. + FakeDNSEnabled bool `json:"fake_dns_enabled,omitempty"` + + // FakeDNSListen is the IPv4/IPv6 UDP address for the built-in local DNS + // listener. For your case use an IPv6 address, for example + // "[2001:db8::1234]:53" or "[::]:53". + FakeDNSListen string `json:"fake_dns_listen,omitempty"` + + // FakeDNSDomain is the local DNSTT zone accepted by the built-in DNS listener. + // If empty while FakeDNSEnabled is true, it defaults to "t.local.lan". + FakeDNSDomain string `json:"fake_dns_domain,omitempty"` + + // FakeDNSWorkers controls how many concurrent UDP read/parse workers are used + // by the built-in local DNS listener. Zero uses a safe automatic default. + FakeDNSWorkers int `json:"fake_dns_workers,omitempty"` + + // DNSResponseWorkers controls how many DNS response sender shards are used. + // Zero keeps the safest default of one sender. Increase carefully only when + // the DNSTT pending queue grows under load. + DNSResponseWorkers int `json:"dns_response_workers,omitempty"` + // PrivKeyFile is the path to the Noise server private key. Generate a + // keypair with the dnstt tool (use -gen-key) and copy the resulting + // private key here; the matching public key must be distributed to + // clients【38494750697905†L172-L209】. + PrivKeyFile string `json:"privkey_file"` + + // DisableStatsLog disables printing of periodic DNSTT statistics to the + // process stderr. When true, the server will still collect tunnel + // counters and expose them via the admin API, but the log lines like + // "dnstt: stats 5s: dns_rx=..." will not appear on the CLI. The default + // is false, meaning stats are printed. This flag is useful when running + // the server in quiet environments where repeated log output should be + // avoided, but visibility into tunnel health is still desired via the + // web panel. + DisableStatsLog bool `json:"disable_stats_log"` + + // DisableConsoleLog disables printing of all DNSTT log lines to stderr. When + // true, messages such as new KCP sessions, smux streams, and SSH stream + // begin/end will not be written to the console. Instead, they are + // captured in an in-memory buffer and surfaced via the admin API for + // display in the web panel. The default is false, meaning logs are + // printed to the console. Set this to true in combination with + // disable_stats_log if you want a fully quiet DNSTT server. + DisableConsoleLog bool `json:"disable_console_log"` + + // AutoRestartInterval controls a watchdog that periodically cycles only the + // integrated DNSTT UDP listener. Empty, "0s", "off", or "disabled" turns it + // off. Valid examples: "30m", "2h", "6h". Minimum accepted value is 1m. + AutoRestartInterval string `json:"auto_restart_interval,omitempty"` + + // AutoRestartGrace is the delay between closing the old DNSTT UDP socket and + // binding a new one during an auto restart. Empty defaults to "2s". + AutoRestartGrace string `json:"auto_restart_grace,omitempty"` + + // MaxSessions limits concurrently open DNSTT/KCP sessions. Zero uses a safe + // default for large public servers. Negative disables the limit. + MaxSessions int `json:"max_sessions,omitempty"` + + // MaxStreams limits concurrently open smux/SSH streams across all DNSTT + // sessions. Zero uses a safe default. Negative disables the limit. + MaxStreams int `json:"max_streams,omitempty"` + + // PendingResponses controls the buffer of queued DNS responses waiting for + // sendLoop. Zero uses the default. Keeping it bounded prevents RAM spikes. + PendingResponses int `json:"pending_responses,omitempty"` + + // StreamBuffer sets smux MaxStreamBuffer in bytes. Zero uses the default. + // Lower values reduce RAM use when thousands of clients are connected. + StreamBuffer int `json:"stream_buffer,omitempty"` + + // UDPReadBuffer and UDPWriteBuffer request OS socket buffers in bytes. Zero + // uses the default. The kernel may clamp these unless sysctl limits are raised. + UDPReadBuffer int `json:"udp_read_buffer,omitempty"` + UDPWriteBuffer int `json:"udp_write_buffer,omitempty"` + + // LogConnections enables per-session and per-stream DNSTT logs. Leave off on + // servers with thousands of users because connection logging can become the + // bottleneck and make crashes more likely. + LogConnections bool `json:"log_connections,omitempty"` +} + +// UDPGWConfig defines the settings for the integrated UDP gateway. The +// gateway accepts TCP connections speaking the BadVPN udpgw protocol and +// forwards framed UDP datagrams to arbitrary IPv4 destinations. All +// fields are optional; if a field is zero or empty, a sensible default +// matching the standalone udpgw implementation is used. +type UDPGWConfig struct { + // Listen is the TCP address to bind for incoming udpgw clients. Use + // IPv6 syntax in brackets when necessary (e.g. "[::]:7400"). If + // empty, the default "0.0.0.0:7400" is used. + Listen string `json:"listen"` + // MaxFrame limits the maximum payload length (in bytes) of a frame sent + // by the client. The default is 64*1024 (64 KiB). Frames larger + // than this are rejected. + MaxFrame int `json:"max_frame"` + // Debug enables verbose logging of connections, frames and + // mappings. + Debug bool `json:"debug"` + // HexdumpN controls how many bytes of each payload are hex‑dumped in + // debug logs. A value of zero suppresses hex dumps. Default is 64. + HexdumpN int `json:"hexdump"` + // WriteChan sets the size of the buffered channel used for sending + // reply frames back to the client. Default and hard ceiling is 1024: + // values above the ceiling are clamped down, so an oversized value left in + // an old config cannot bloat per-client memory. Zero uses the default. + WriteChan int `json:"write_chan"` + // UDPBindIP, if non‑empty, causes each per‑client UDP socket to bind to + // the specified local IP address. The port is chosen automatically. + UDPBindIP string `json:"udp_bind"` + // UDPRBuf sets the per-client UDP socket read buffer in bytes. This is + // KERNEL memory allocated per connected client. Default and hard ceiling is + // 512 KiB; larger values (including old 8 MiB configs) are clamped down so + // thousands of clients cannot exhaust kernel memory. Zero uses the default. + UDPRBuf int `json:"udp_rbuf"` + // UDPWBuf sets the per-client UDP socket write buffer in bytes. Default and + // hard ceiling is 512 KiB; larger values are clamped down. Zero uses the + // default. + UDPWBuf int `json:"udp_wbuf"` + // MapTTL controls how long a destination->connID mapping remains + // valid after the last packet from that destination. Expressed as a + // duration string. Default is "90s". + MapTTL string `json:"map_ttl"` + // ReapEvery controls how often expired mappings are purged. Expressed + // as a duration string. Default is "10s". + ReapEvery string `json:"reap_every"` + // IdleTimeout controls how long a TCP client connection may remain + // idle (no frames received) before being closed. Expressed as a duration + // string. Default is "2m". + IdleTimeout string `json:"idle_timeout"` + // MaxClientConns limits how many distinct udpgw connIDs a single TCP + // client connection may keep active at once. This is the primary guard + // against a single client creating effectively infinite logical UDP + // sessions and growing RAM usage over time. Default is 10. + MaxClientConns int `json:"max_client_conns"` + // MaxMapEntries limits the maximum number of destination->connID + // mappings kept per client. This protects the server from unbounded + // growth if a client sprays packets to many unique destinations. + // Default is 32768. + MaxMapEntries int `json:"max_map_entries"` + // MaxClients caps the total number of concurrent UDPGW client TCP + // connections. Once reached, new clients are rejected (their TCP socket is + // closed immediately) instead of being accepted, so a surge past normal + // load cannot exhaust memory and crash the server. Default is 10000. + // A value <= 0 uses the default. + MaxClients int `json:"max_clients"` + + // AutoRestartInterval controls a watchdog that periodically hard-restarts + // the integrated UDPGW listener and closes all connected UDPGW clients. Empty, + // "0s", "off", or "disabled" turns it off. Valid examples: "30m", "6h", "24h". + // Minimum accepted value is 1m. + AutoRestartInterval string `json:"auto_restart_interval,omitempty"` + + // AutoRestartGrace is the delay between closing the old UDPGW listener/clients + // and binding a new one during an auto restart. Empty defaults to "2s". + AutoRestartGrace string `json:"auto_restart_grace,omitempty"` +} + +type UserConfig struct { + Username string `json:"username"` + Password string `json:"password"` + PublicKeyFile string `json:"public_key_file"` // optional .pub path + + // Optional rotating password mode for shared/public accounts. When + // totp_secret is set, the server accepts a TOTP code as the SSH + // password. This is useful when you want to make copied credentials + // expire quickly without relying on a separate API. + // Secret must be Base32 (with or without padding). Example generated + // secret: JBSWY3DPEHPK3PXP + TOTPSecret string `json:"totp_secret"` + // Period in seconds for each password step. Default: 60. + TOTPPeriod int `json:"totp_period"` + // Number of adjacent time windows accepted for clock drift. + // Default: 1 (previous/current/next). + TOTPWindow int `json:"totp_window"` + // Number of digits in the generated TOTP. Default: 6. + TOTPDigits int `json:"totp_digits"` + // When true, both the static Password and the TOTP code are accepted. + // When false and totp_secret is set, only the TOTP code is accepted. + AllowStaticPassword bool `json:"allow_static_password"` + + // UsePAM is a legacy opt-in: when true, the supplied SSH password is + // verified against the Linux PAM auth stack (auth phase only) for the + // system account matching this username, instead of the panel-managed + // Password/TOTP. New users leave this false and keep the script's own auth. + UsePAM bool `json:"use_pam"` + + MaxConnections int `json:"max_connections"` + ExpiresAt string `json:"expires_at"` // RFC3339 or empty + + // Per-connection limits (one limiter per SSH connection) + LimitMbpsUp int `json:"limit_mbps_up"` // Mbps upstream + LimitMbpsDown int `json:"limit_mbps_down"` // Mbps downstream + + // Persistent data quota. Zero means unlimited. When the total uploaded + + // downloaded bytes reaches the quota, QuotaAction either blocks traffic or + // throttles the account to QuotaThrottleMbps. + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + + // OwnerUsername is the reseller who created this SSH user. Empty = superadmin-owned. + OwnerUsername string `json:"owner_username,omitempty"` +} + +type UserState struct { + Cfg UserConfig + ExpiresAt *time.Time + PubKey ssh.PublicKey // may be nil + + mu sync.Mutex + ActiveConns int + conns map[*ssh.ServerConn]struct{} // active SSH connections for this user + // btunConns counts active BTUN sessions for this user. BTUN carries IP + // packets instead of an SSH stream, so it has no *ssh.ServerConn to track; + // it shares max_connections with SSH through this counter. + btunConns int + + // Persistent per-user tunnel traffic. totalBytes includes reservations made + // by concurrent copy loops, while directional totals only include bytes that + // were actually written. The pending counters are flushed to PostgreSQL. + TotalUplinkBytes int64 + TotalDownlinkBytes int64 + totalBytes int64 + pendingUplinkBytes int64 + pendingDownlinkBytes int64 + trafficMu sync.RWMutex + quotaLimiter *rate.Limiter + quotaLimiterMbps int +} + +type UserManager struct { + mu sync.RWMutex + users map[string]*UserState +} + +func (m *UserManager) Get(username string) (*UserState, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + u, ok := m.users[username] + return u, ok +} + +// AddIfAbsent inserts u only if no user with the same username exists yet, and +// reports whether it was added. Used by PAM auto-import to register a freshly +// authenticated system account without clobbering an existing runtime state. +func (m *UserManager) AddIfAbsent(u *UserState) bool { + m.mu.Lock() + defer m.mu.Unlock() + if _, exists := m.users[u.Cfg.Username]; exists { + return false + } + m.users[u.Cfg.Username] = u + return true +} + +func (m *UserManager) List() []*UserState { + m.mu.RLock() + defer m.mu.RUnlock() + out := make([]*UserState, 0, len(m.users)) + for _, u := range m.users { + out = append(out, u) + } + return out +} + +func (m *UserManager) ReplaceAll(newUsers map[string]*UserState) { + m.mu.Lock() + defer m.mu.Unlock() + m.users = newUsers +} + +// ReplaceAllPreserveRuntime replaces the user map while keeping the same +// runtime UserState object for users that already exist. This is important: +// active handleConn goroutines hold a pointer to the old UserState and run the +// decrement in a defer. If we copy ActiveConns into a new UserState during a DB +// reload, that later decrement happens on the old object and the visible count +// in the new map stays stuck. +func (m *UserManager) ReplaceAllPreserveRuntime(newUsers map[string]*UserState) { + m.mu.Lock() + old := m.users + + for username, nu := range newUsers { + if ou, ok := old[username]; ok && ou != nil && nu != nil { + ou.mu.Lock() + ou.Cfg = nu.Cfg + ou.ExpiresAt = nu.ExpiresAt + ou.PubKey = nu.PubKey + if ou.conns == nil { + ou.conns = make(map[*ssh.ServerConn]struct{}) + } + // Self-heal any previously stale counter by trusting the live connection map. + ou.ActiveConns = len(ou.conns) + ou.btunConns + ou.mu.Unlock() + + newUsers[username] = ou + } + } + + m.users = newUsers + m.mu.Unlock() +} + +// DisconnectUser closes all active SSH connections for the given user. +// Safe if the user does not exist or has no connections. +func (m *UserManager) DisconnectUser(username string) { + m.mu.RLock() + u, ok := m.users[username] + m.mu.RUnlock() + if !ok { + return + } + + u.mu.Lock() + conns := make([]*ssh.ServerConn, 0, len(u.conns)) + for c := range u.conns { + conns = append(conns, c) + } + u.mu.Unlock() + + for _, c := range conns { + _ = c.Close() + } + // BTUN sessions belong to the same account allowance, so a panel-driven + // disconnect has to drop them too. + btunDisconnectUser(username) +} + +// DisconnectAll closes every authenticated SSH connection currently tracked by +// the user manager. It is used by the proxy hard auto-restart to mimic a real +// service reboot instead of only reopening listening sockets. +func (m *UserManager) DisconnectAll() int { + m.mu.RLock() + states := make([]*UserState, 0, len(m.users)) + for _, u := range m.users { + states = append(states, u) + } + m.mu.RUnlock() + + seen := make(map[*ssh.ServerConn]struct{}) + for _, u := range states { + if u == nil { + continue + } + u.mu.Lock() + for c := range u.conns { + seen[c] = struct{}{} + } + u.mu.Unlock() + } + + for c := range seen { + _ = c.Close() + } + return len(seen) + btunDisconnectAll() +} + +// Global state +var ( + userMgr = &UserManager{users: make(map[string]*UserState)} + userCountEnabled bool + + sshIdleTimeoutMu sync.RWMutex + currentSSHIdleTimeout = defaultSSHIdleTimeout + + displayMu sync.Mutex + lastDisplayLen int + + // Server stats (CPU + network interfaces) + statsMu sync.RWMutex + currentStats StatsDTO + + // Optional: persist interface byte counters across process restarts / reboots (requires PG_DSN). + ifaceTotalsMgr *IfaceTotalsManager + statsStore *Store +) + +// ---------- Helpers ---------- + +func publicKeysEqual(a, b ssh.PublicKey) bool { + if a == nil || b == nil { + return a == b + } + return a.Type() == b.Type() && bytes.Equal(a.Marshal(), b.Marshal()) +} + +func mbpsToBytesPerSec(mbps int) int64 { + if mbps <= 0 { + return 0 + } + return int64(mbps) * 1024 * 1024 / 8 +} + +// copyBufSize is the per-direction relay buffer for tunnel traffic. SSH tunnel +// clients (mobile injection apps) push many low-bandwidth flows, so a large +// buffer wastes heap with no throughput benefit. 16 KiB keeps per-channel heap +// low across thousands of concurrent direct-tcpip channels. +const copyBufSize = 16 * 1024 + +var copyBufPool = sync.Pool{ + New: func() interface{} { b := make([]byte, copyBufSize); return &b }, +} + +// copyWithRateLimit relays src->dst through a pooled buffer. Every copy path +// (rate-limited or not) goes through the pool: previously the lim==nil path used +// io.Copy, which allocates a fresh 32 KiB buffer per direction per channel and +// never pools it — at thousands of channels that churn dominated GC pressure. +func copyWithRateLimit(dst io.Writer, src io.Reader, lim *rate.Limiter) (written int64, err error) { + return copyWithRateLimitContext(context.Background(), dst, src, lim) +} + +func copyWithRateLimitContext(ctx context.Context, dst io.Writer, src io.Reader, lim *rate.Limiter) (written int64, err error) { + bufp := copyBufPool.Get().(*[]byte) + buf := *bufp + defer copyBufPool.Put(bufp) + + if ctx == nil { + ctx = context.Background() + } + + for { + nr, er := src.Read(buf) + if nr > 0 { + if lim != nil { + if err := lim.WaitN(ctx, nr); err != nil { + return written, err + } + } + + nw, ew := dst.Write(buf[:nr]) + if nw > 0 { + written += int64(nw) + } + if ew != nil { + err = ew + break + } + if nr != nw { + err = io.ErrShortWrite + break + } + } + + if er != nil { + if er != io.EOF { + err = er + } + break + } + } + + return written, err +} + +func parseSSHIdleTimeout(raw string) time.Duration { + raw = strings.TrimSpace(raw) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + log.Printf("invalid ssh_idle_timeout %q: %v; disabling SSH idle timeout", raw, err) + return 0 + } + if d < 0 { + log.Printf("invalid negative ssh_idle_timeout %q; disabling SSH idle timeout", raw) + return 0 + } + return d +} + +func setSSHIdleTimeoutFromConfig(raw string) { + d := parseSSHIdleTimeout(raw) + sshIdleTimeoutMu.Lock() + currentSSHIdleTimeout = d + sshIdleTimeoutMu.Unlock() +} + +func getSSHIdleTimeout() time.Duration { + sshIdleTimeoutMu.RLock() + d := currentSSHIdleTimeout + sshIdleTimeoutMu.RUnlock() + return d +} + +// defaultMaxTotalConns is the global concurrent SSH connection cap used when +// max_total_connections is unset (0). Keeps headroom above normal load while +// preventing an unbounded surge from exhausting memory/CPU. +const defaultMaxTotalConns = 10000 + +var ( + // activeSSHConns is the current number of in-flight SSH connections. + activeSSHConns int64 + // maxTotalConns is the global cap; 0 means unlimited. Set from config. + maxTotalConns int64 = defaultMaxTotalConns + // sshConnsRejected counts connections turned away at the global cap. + sshConnsRejected int64 +) + +// setMaxTotalConnsFromConfig applies the max_total_connections config value: +// 0 -> default, <0 -> disabled (unlimited), >0 -> that exact cap. +func setMaxTotalConnsFromConfig(v int) { + var lim int64 + switch { + case v < 0: + lim = 0 + case v == 0: + lim = defaultMaxTotalConns + default: + lim = int64(v) + } + atomic.StoreInt64(&maxTotalConns, lim) +} + +// activityConn tracks real SSH transport activity in both directions. The idle +// monitor uses this instead of a read deadline so download-only or upload-only +// tunnels are considered live and are not disconnected. +type activityConn struct { + net.Conn + mu sync.Mutex + last time.Time +} + +func newActivityConn(c net.Conn) *activityConn { + return &activityConn{Conn: c, last: time.Now()} +} + +func (c *activityConn) touch() { + c.mu.Lock() + c.last = time.Now() + c.mu.Unlock() +} + +func (c *activityConn) LastActivity() time.Time { + c.mu.Lock() + last := c.last + c.mu.Unlock() + return last +} + +func (c *activityConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + c.touch() + } + return n, err +} + +func (c *activityConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + if n > 0 { + c.touch() + } + return n, err +} + +func monitorSSHIdle(c *activityConn, sshConn *ssh.ServerConn, username string, idleTimeout time.Duration, done <-chan struct{}) { + if idleTimeout <= 0 { + return + } + checkEvery := idleTimeout / 4 + if checkEvery < 5*time.Second { + checkEvery = 5 * time.Second + } + if checkEvery > 30*time.Second { + checkEvery = 30 * time.Second + } + + ticker := time.NewTicker(checkEvery) + defer ticker.Stop() + + for { + select { + case <-done: + return + case <-ticker.C: + idleFor := time.Since(c.LastActivity()) + if idleFor >= idleTimeout { + log.Printf("ssh idle timeout: user=%s remote=%s idle=%s limit=%s; closing stale connection", + username, sshConn.RemoteAddr(), idleFor.Round(time.Second), idleTimeout) + _ = sshConn.Close() + _ = c.Close() + return + } + } + } +} + +// ---------- Server stats (CPU + network interfaces) ---------- + +// per-interface stats returned by /api/stats +type InterfaceStats struct { + Name string `json:"name"` + RxBytes uint64 `json:"rx_bytes"` + TxBytes uint64 `json:"tx_bytes"` + RxMbps float64 `json:"rx_mbps"` + TxMbps float64 `json:"tx_mbps"` +} + +type StatsDTO struct { + CPUPercent float64 `json:"cpu_percent"` + MemTotal uint64 `json:"mem_total_bytes"` + MemUsed uint64 `json:"mem_used_bytes"` + MemAvail uint64 `json:"mem_avail_bytes"` + MemPercent float64 `json:"mem_percent"` + Interfaces []InterfaceStats `json:"interfaces"` +} +type ifaceCounters struct { + RxBytes uint64 + TxBytes uint64 +} + +func isIgnoredInterface(iface string) bool { + return iface == "" || iface == "lo" +} + +func getCurrentStats() StatsDTO { + statsMu.RLock() + defer statsMu.RUnlock() + return currentStats +} + +func setCurrentStats(s StatsDTO) { + statsMu.Lock() + currentStats = s + statsMu.Unlock() +} + +// primeCurrentStats fills RAM and interface totals immediately at startup so +// the dashboard does not show placeholder values while waiting for the first +// polling interval. CPU still becomes accurate after the second /proc/stat +// sample, but it is rendered as 0.0% instead of --. +func primeCurrentStats() { + netMap, _ := readNetDev() + interfaces := make([]InterfaceStats, 0, len(netMap)) + for name, ctrs := range netMap { + if isIgnoredInterface(name) { + continue + } + st := InterfaceStats{Name: name} + if ifaceTotalsMgr != nil { + rxTotal, txTotal := ifaceTotalsMgr.ApplyKernel(name, ctrs.RxBytes, ctrs.TxBytes) + st.RxBytes = rxTotal + st.TxBytes = txTotal + } else { + st.RxBytes = ctrs.RxBytes + st.TxBytes = ctrs.TxBytes + } + interfaces = append(interfaces, st) + } + sort.Slice(interfaces, func(i, j int) bool { return interfaces[i].Name < interfaces[j].Name }) + memTotal, memAvail, _ := readMemInfo() + var memUsed uint64 + var memPercent float64 + if memTotal > 0 { + if memAvail <= memTotal { + memUsed = memTotal - memAvail + memPercent = 100.0 * float64(memUsed) / float64(memTotal) + } + } + setCurrentStats(StatsDTO{ + CPUPercent: 0, + MemTotal: memTotal, + MemUsed: memUsed, + MemAvail: memAvail, + MemPercent: memPercent, + Interfaces: interfaces, + }) +} + +type IfaceTotals struct { + Iface string + TotalRxBytes uint64 + TotalTxBytes uint64 + LastKernelRxBytes uint64 + LastKernelTxBytes uint64 + UpdatedAt time.Time + ResetAt time.Time +} + +type IfaceTotalsManager struct { + mu sync.Mutex + m map[string]*IfaceTotals +} + +func NewIfaceTotalsManager() *IfaceTotalsManager { + return &IfaceTotalsManager{m: make(map[string]*IfaceTotals)} +} + +// ApplyKernel updates cumulative totals using kernel counters (from /proc/net/dev). +// It is resilient to kernel counter resets (e.g. host reboot): if the kernel counter +// goes backwards, it treats the new value as "delta since reset". +func (tm *IfaceTotalsManager) ApplyKernel(iface string, kRx, kTx uint64) (totalRx, totalTx uint64) { + if isIgnoredInterface(iface) { + return 0, 0 + } + tm.mu.Lock() + defer tm.mu.Unlock() + + now := time.Now() + st, ok := tm.m[iface] + if !ok { + st = &IfaceTotals{Iface: iface, ResetAt: now} + tm.m[iface] = st + } + if st.ResetAt.IsZero() { + st.ResetAt = now + } + + // The live interface counters in the Stats tab are a rolling 30-day total. + // This reset does not touch the vnstat-style daily/monthly history tables. + if now.Sub(st.ResetAt) >= 30*24*time.Hour { + st.TotalRxBytes = 0 + st.TotalTxBytes = 0 + st.LastKernelRxBytes = kRx + st.LastKernelTxBytes = kTx + st.ResetAt = now + st.UpdatedAt = now + return 0, 0 + } + + // RX + if st.LastKernelRxBytes == 0 && st.TotalRxBytes == 0 { + st.TotalRxBytes = kRx + } else if kRx >= st.LastKernelRxBytes { + st.TotalRxBytes += kRx - st.LastKernelRxBytes + } else { + // kernel reset or wrap + st.TotalRxBytes += kRx + } + st.LastKernelRxBytes = kRx + + // TX + if st.LastKernelTxBytes == 0 && st.TotalTxBytes == 0 { + st.TotalTxBytes = kTx + } else if kTx >= st.LastKernelTxBytes { + st.TotalTxBytes += kTx - st.LastKernelTxBytes + } else { + st.TotalTxBytes += kTx + } + st.LastKernelTxBytes = kTx + + st.UpdatedAt = now + return st.TotalRxBytes, st.TotalTxBytes +} + +func (tm *IfaceTotalsManager) ResetAllToKernel(netMap map[string]ifaceCounters) []IfaceTotals { + tm.mu.Lock() + defer tm.mu.Unlock() + + now := time.Now() + tm.m = make(map[string]*IfaceTotals, len(netMap)) + out := make([]IfaceTotals, 0, len(netMap)) + for iface, ctrs := range netMap { + if isIgnoredInterface(iface) { + continue + } + st := &IfaceTotals{ + Iface: iface, + TotalRxBytes: 0, + TotalTxBytes: 0, + LastKernelRxBytes: ctrs.RxBytes, + LastKernelTxBytes: ctrs.TxBytes, + UpdatedAt: now, + ResetAt: now, + } + tm.m[iface] = st + out = append(out, *st) + } + return out +} + +func (tm *IfaceTotalsManager) Load(rows []IfaceTotals) { + tm.mu.Lock() + defer tm.mu.Unlock() + for _, r := range rows { + if isIgnoredInterface(r.Iface) { + continue + } + cp := r // copy + tm.m[r.Iface] = &cp + } +} + +func (tm *IfaceTotalsManager) Snapshot() []IfaceTotals { + tm.mu.Lock() + defer tm.mu.Unlock() + out := make([]IfaceTotals, 0, len(tm.m)) + for _, v := range tm.m { + if v == nil || isIgnoredInterface(v.Iface) { + continue + } + out = append(out, *v) + } + return out +} + +// startStatsCollector periodically reads /proc/stat and /proc/net/dev +// to compute CPU usage and per-interface traffic in Mbps. +func startStatsCollector() { + go func() { + // Recover from any panic so the goroutine doesn't silently die and + // leave stats frozen. Log the panic and restart after a short delay. + defer func() { + if r := recover(); r != nil { + log.Printf("startStatsCollector: panic recovered: %v; restarting in 5s", r) + time.Sleep(5 * time.Second) + go startStatsCollector() + } + }() + + var ( + prevIdle, prevTotal uint64 + prevNet map[string]ifaceCounters + prevTime time.Time + ) + + // Use a ticker for the poll interval so the goroutine can be + // cleanly stopped in tests and so the flush ticker is always + // paired with a matching Stop(). + pollTicker := time.NewTicker(2 * time.Second) + defer pollTicker.Stop() + + var flushTicker *time.Ticker + if statsStore != nil && ifaceTotalsMgr != nil { + flushTicker = time.NewTicker(30 * time.Second) + defer flushTicker.Stop() + } + + for range pollTicker.C { + now := time.Now() + + idle, total, err := readCPUStat() + if err != nil { + // keep previous CPU if error + } + + netMap, err := readNetDev() + if err != nil { + // keep previous net if error + } + + // CPU usage + var cpuPercent float64 + if prevTotal != 0 && total > prevTotal { + idleDelta := float64(idle - prevIdle) + totalDelta := float64(total - prevTotal) + if totalDelta > 0 { + cpuPercent = 100.0 * (1.0 - idleDelta/totalDelta) + } + } + + // Per-interface Mbps (Rx/Tx) + var interfaces []InterfaceStats + dt := now.Sub(prevTime).Seconds() + if netMap != nil { + for name, ctrs := range netMap { + if isIgnoredInterface(name) { + continue + } + st := InterfaceStats{ + Name: name, + } + // Bytes: if persistence enabled, show cumulative totals across restarts; else show kernel counters. + if ifaceTotalsMgr != nil { + rxTotal, txTotal := ifaceTotalsMgr.ApplyKernel(name, ctrs.RxBytes, ctrs.TxBytes) + st.RxBytes = rxTotal + st.TxBytes = txTotal + } else { + st.RxBytes = ctrs.RxBytes + st.TxBytes = ctrs.TxBytes + } + if prevNet != nil && dt > 0 { + if prev, ok := prevNet[name]; ok { + var rxDelta, txDelta uint64 + if ctrs.RxBytes >= prev.RxBytes { + rxDelta = ctrs.RxBytes - prev.RxBytes + } else { + // kernel counter reset or wrap + rxDelta = ctrs.RxBytes + } + if ctrs.TxBytes >= prev.TxBytes { + txDelta = ctrs.TxBytes - prev.TxBytes + } else { + txDelta = ctrs.TxBytes + } + if rxDelta > 0 { + st.RxMbps = float64(rxDelta*8) / dt / 1_000_000 + } + if txDelta > 0 { + st.TxMbps = float64(txDelta*8) / dt / 1_000_000 + } + if statsStore != nil && (rxDelta > 0 || txDelta > 0) { + addPendingIfaceUsage(name, rxDelta, txDelta) + } + } + } + interfaces = append(interfaces, st) + } + } + + sort.Slice(interfaces, func(i, j int) bool { + return interfaces[i].Name < interfaces[j].Name + }) + + // RAM usage (/proc/meminfo) + memTotal, memAvail, _ := readMemInfo() + var memUsed uint64 + var memPercent float64 + if memTotal > 0 { + if memAvail <= memTotal { + memUsed = memTotal - memAvail + memPercent = 100.0 * float64(memUsed) / float64(memTotal) + } else { + memAvail = memTotal + } + } + + setCurrentStats(StatsDTO{ + CPUPercent: cpuPercent, + MemTotal: memTotal, + MemUsed: memUsed, + MemAvail: memAvail, + MemPercent: memPercent, + Interfaces: interfaces, + }) + + // Persist interface totals and vnstat-style usage periodically (optional). + if flushTicker != nil && statsStore != nil && ifaceTotalsMgr != nil { + select { + case <-flushTicker.C: + ctx := context.Background() + _ = statsStore.UpsertIfaceTotals(ctx, ifaceTotalsMgr.Snapshot()) + if deltas := flushPendingIfaceUsage(now); len(deltas) > 0 { + if err := statsStore.UpsertIfaceUsageDeltas(ctx, deltas); err != nil { + log.Printf("vnstat usage flush failed: %v", err) + restorePendingIfaceUsage(deltas) + } + } + default: + } + } + + prevIdle, prevTotal = idle, total + prevNet = netMap + prevTime = now + } + }() +} + +func readMemInfo() (totalBytes, availBytes uint64, err error) { + f, err := os.Open("/proc/meminfo") + if err != nil { + return 0, 0, err + } + defer f.Close() + + var ( + memTotalKB uint64 + memAvailKB uint64 + memFreeKB uint64 + buffersKB uint64 + cachedKB uint64 + ) + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Text() + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + key := strings.TrimSuffix(fields[0], ":") + val, perr := strconv.ParseUint(fields[1], 10, 64) + if perr != nil { + continue + } + switch key { + case "MemTotal": + memTotalKB = val + case "MemAvailable": + memAvailKB = val + case "MemFree": + memFreeKB = val + case "Buffers": + buffersKB = val + case "Cached": + cachedKB = val + } + } + if err := scanner.Err(); err != nil { + return 0, 0, err + } + if memTotalKB == 0 { + return 0, 0, nil + } + if memAvailKB == 0 { + memAvailKB = memFreeKB + buffersKB + cachedKB + if memAvailKB > memTotalKB { + memAvailKB = memTotalKB + } + } + return memTotalKB * 1024, memAvailKB * 1024, nil +} + +func readCPUStat() (idle, total uint64, err error) { + f, err := os.Open("/proc/stat") + if err != nil { + return 0, 0, err + } + defer f.Close() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "cpu ") { + fields := strings.Fields(line) + if len(fields) < 5 { + break + } + for i := 1; i < len(fields); i++ { + v, err2 := strconv.ParseUint(fields[i], 10, 64) + if err2 != nil { + continue + } + total += v + // idle + iowait + if i == 4 || i == 5 { + idle += v + } + } + break + } + } + if err := scanner.Err(); err != nil { + return 0, 0, err + } + return idle, total, nil +} + +func readNetDev() (map[string]ifaceCounters, error) { + f, err := os.Open("/proc/net/dev") + if err != nil { + return nil, err + } + defer f.Close() + + stats := make(map[string]ifaceCounters) + scanner := bufio.NewScanner(f) + lineNum := 0 + for scanner.Scan() { + lineNum++ + if lineNum <= 2 { + // headers + continue + } + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + parts := strings.SplitN(line, ":", 2) + if len(parts) != 2 { + continue + } + iface := strings.TrimSpace(parts[0]) + if isIgnoredInterface(iface) { + continue + } + fields := strings.Fields(parts[1]) + if len(fields) < 9 { + continue + } + rx, err1 := strconv.ParseUint(fields[0], 10, 64) + tx, err2 := strconv.ParseUint(fields[8], 10, 64) + if err1 != nil || err2 != nil { + continue + } + stats[iface] = ifaceCounters{ + RxBytes: rx, + TxBytes: tx, + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return stats, nil +} + +// ---------- Config loading ---------- + +const defaultInstalledConfigPath = "/opt/sshpanel/config.json" + +func resolveMainConfigPath(path string) string { + path = strings.TrimSpace(path) + if path != "" { + return path + } + if _, err := os.Stat("config.json"); err == nil { + return "config.json" + } + return defaultInstalledConfigPath +} + +func loadConfig(path string) (*Config, map[string]*UserState, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, nil, fmt.Errorf("read config: %w", err) + } + + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, nil, fmt.Errorf("parse config: %w", err) + } + if cfg.Xray != nil { + cfg.Xray.NormalizeDefaults() + } + + if cfg.Listen == "" { + cfg.Listen = defaultMainListen + } + if cfg.HostKeyFile == "" { + cfg.HostKeyFile = "ssh_host_rsa_key" + } + + userMap := make(map[string]*UserState) + for _, u := range cfg.Users { + if u.Username == "" { + return nil, nil, fmt.Errorf("config: user with empty username") + } + if _, exists := userMap[u.Username]; exists { + return nil, nil, fmt.Errorf("config: duplicate user %q", u.Username) + } + + // Apply default bandwidth limits if not set per-user. + if u.LimitMbpsUp == 0 { + u.LimitMbpsUp = cfg.DefaultLimitMbpsUp + } + if u.LimitMbpsDown == 0 { + u.LimitMbpsDown = cfg.DefaultLimitMbpsDown + } + + st := &UserState{Cfg: u} + + if u.ExpiresAt != "" { + t, err := time.Parse(time.RFC3339, u.ExpiresAt) + if err != nil { + return nil, nil, fmt.Errorf("config: invalid expires_at for user %q: %w", u.Username, err) + } + st.ExpiresAt = &t + } + + // Load per-user public key if configured + if u.PublicKeyFile != "" { + pkBytes, err := os.ReadFile(u.PublicKeyFile) + if err != nil { + return nil, nil, fmt.Errorf("config: could not read public_key_file for user %q: %w", u.Username, err) + } + pubKey, _, _, _, err := ssh.ParseAuthorizedKey(pkBytes) + if err != nil { + return nil, nil, fmt.Errorf("config: invalid public key in %s for user %q: %w", + u.PublicKeyFile, u.Username, err) + } + st.PubKey = pubKey + } + + userMap[u.Username] = st + } + + return &cfg, userMap, nil +} + +// ---------- Database store & admin API ---------- + +type Store struct { + db *sql.DB +} + +func NewStore(dsn string) (*Store, error) { + db, err := sql.Open("postgres", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(5) + db.SetMaxIdleConns(5) + db.SetConnMaxLifetime(time.Hour) + + if err := db.Ping(); err != nil { + return nil, err + } + store := &Store{db: db} + ctx := context.Background() + if err := store.EnsureUsersSchema(ctx); err != nil { + return nil, err + } + if err := store.EnsureAdminUsersSchema(ctx); err != nil { + return nil, err + } + if err := store.EnsureManagedServersSchema(ctx); err != nil { + return nil, err + } + if err := store.EnsureBotSchema(ctx); err != nil { + return nil, err + } + return store, nil +} + +const sshPasswordPrefix = "enc:v1:ssh:" + +func sealSSHPassword(password string) (string, error) { + return sealCredential(sshPasswordPrefix, password) +} + +func openSSHPassword(password string) (string, error) { + return openCredential(sshPasswordPrefix, password) +} + +func (s *Store) EnsureUsersSchema(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS ssh_users ( + username TEXT PRIMARY KEY, + password TEXT NOT NULL DEFAULT '', + max_connections INT NOT NULL DEFAULT 0, + expires_at TEXT, + limit_mbps_up INT NOT NULL DEFAULT 0, + limit_mbps_down INT NOT NULL DEFAULT 0, + data_quota_bytes BIGINT NOT NULL DEFAULT 0, + quota_action TEXT NOT NULL DEFAULT 'block', + quota_throttle_mbps INT NOT NULL DEFAULT 1, + total_uplink_bytes BIGINT NOT NULL DEFAULT 0, + total_downlink_bytes BIGINT NOT NULL DEFAULT 0, + totp_secret TEXT NOT NULL DEFAULT '', + totp_period INT NOT NULL DEFAULT 60, + totp_window INT NOT NULL DEFAULT 1, + totp_digits INT NOT NULL DEFAULT 6, + allow_static_password BOOLEAN NOT NULL DEFAULT FALSE, + use_pam BOOLEAN NOT NULL DEFAULT FALSE + )`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_period INT NOT NULL DEFAULT 60`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_window INT NOT NULL DEFAULT 1`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_digits INT NOT NULL DEFAULT 6`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS allow_static_password BOOLEAN NOT NULL DEFAULT FALSE`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS use_pam BOOLEAN NOT NULL DEFAULT FALSE`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS data_quota_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS quota_action TEXT NOT NULL DEFAULT 'block'`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS quota_throttle_mbps INT NOT NULL DEFAULT 1`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS total_uplink_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS total_downlink_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE ssh_users ALTER COLUMN password SET DEFAULT ''`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return s.migrateSSHPasswords(ctx) +} + +func (s *Store) migrateSSHPasswords(ctx context.Context) error { + rows, err := s.db.QueryContext(ctx, `SELECT username, password FROM ssh_users WHERE password <> '' AND password NOT LIKE 'enc:v1:ssh:%'`) + if err != nil { + return err + } + type legacyPassword struct { + username string + password string + } + var legacy []legacyPassword + for rows.Next() { + var item legacyPassword + if err := rows.Scan(&item.username, &item.password); err != nil { + rows.Close() + return err + } + legacy = append(legacy, item) + } + if err := rows.Close(); err != nil { + return err + } + for _, item := range legacy { + sealed, err := sealSSHPassword(item.password) + if err != nil { + return fmt.Errorf("encrypt SSH password for %s: %w", item.username, err) + } + if _, err := s.db.ExecContext(ctx, `UPDATE ssh_users SET password=$2 WHERE username=$1`, item.username, sealed); err != nil { + return err + } + } + return nil +} + +// LoadUsers loads all users from the ssh_users table into in-memory UserState map. +func (s *Store) LoadUsers(ctx context.Context) (map[string]*UserState, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT username, password, max_connections, expires_at, limit_mbps_up, limit_mbps_down, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), + COALESCE(totp_secret, ''), COALESCE(totp_period, 60), COALESCE(totp_window, 1), + COALESCE(totp_digits, 6), COALESCE(allow_static_password, FALSE), + COALESCE(use_pam, FALSE), COALESCE(owner_username, '') + FROM ssh_users`) + if err != nil { + return nil, err + } + defer rows.Close() + + users := make(map[string]*UserState) + for rows.Next() { + var ( + username string + password string + maxConnections int + expiresAt sql.NullString + limitUp int + limitDown int + dataQuotaBytes int64 + quotaAction string + quotaThrottleMbps int + totalUplinkBytes int64 + totalDownlinkBytes int64 + totpSecret string + totpPeriod int + totpWindow int + totpDigits int + allowStaticPassword bool + usePAM bool + ownerUsername string + ) + if err := rows.Scan(&username, &password, &maxConnections, &expiresAt, &limitUp, &limitDown, + &dataQuotaBytes, "aAction, "aThrottleMbps, &totalUplinkBytes, &totalDownlinkBytes, + &totpSecret, &totpPeriod, &totpWindow, &totpDigits, &allowStaticPassword, &usePAM, &ownerUsername); err != nil { + return nil, err + } + password, err = openSSHPassword(password) + if err != nil { + return nil, fmt.Errorf("decrypt SSH password for %s: %w", username, err) + } + + cfg := UserConfig{ + Username: username, + Password: password, + MaxConnections: maxConnections, + LimitMbpsUp: limitUp, + LimitMbpsDown: limitDown, + DataQuotaBytes: dataQuotaBytes, + QuotaAction: normalizeQuotaAction(quotaAction), + QuotaThrottleMbps: quotaThrottleMbps, + TOTPSecret: totpSecret, + TOTPPeriod: totpPeriod, + TOTPWindow: totpWindow, + TOTPDigits: totpDigits, + AllowStaticPassword: allowStaticPassword, + UsePAM: usePAM, + OwnerUsername: ownerUsername, + } + + st := &UserState{Cfg: cfg} + initSSHRuntimeUsage(st, totalUplinkBytes, totalDownlinkBytes) + if expiresAt.Valid && expiresAt.String != "" { + t, err := time.Parse(time.RFC3339, expiresAt.String) + if err != nil { + log.Printf("invalid expires_at for user %s in db: %v", username, err) + } else { + st.ExpiresAt = &t + st.Cfg.ExpiresAt = expiresAt.String + } + } + users[username] = st + } + if err := rows.Err(); err != nil { + return nil, err + } + return users, nil +} + +// UpsertUser creates or updates a row in ssh_users. +func (s *Store) UpsertUser(ctx context.Context, u UserConfig) error { + storedPassword, err := sealSSHPassword(u.Password) + if err != nil { + return fmt.Errorf("encrypt SSH password: %w", err) + } + _, err = s.db.ExecContext(ctx, ` + INSERT INTO ssh_users ( + username, password, max_connections, expires_at, limit_mbps_up, limit_mbps_down, + data_quota_bytes, quota_action, quota_throttle_mbps, + totp_secret, totp_period, totp_window, totp_digits, allow_static_password, use_pam, owner_username + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) + ON CONFLICT (username) DO UPDATE + SET password = EXCLUDED.password, + max_connections = EXCLUDED.max_connections, + expires_at = EXCLUDED.expires_at, + limit_mbps_up = EXCLUDED.limit_mbps_up, + limit_mbps_down = EXCLUDED.limit_mbps_down, + data_quota_bytes = EXCLUDED.data_quota_bytes, + quota_action = EXCLUDED.quota_action, + quota_throttle_mbps = EXCLUDED.quota_throttle_mbps, + totp_secret = EXCLUDED.totp_secret, + totp_period = EXCLUDED.totp_period, + totp_window = EXCLUDED.totp_window, + totp_digits = EXCLUDED.totp_digits, + allow_static_password = EXCLUDED.allow_static_password, + use_pam = EXCLUDED.use_pam`, + // owner_username is intentionally excluded from UPDATE — ownership is set at creation only. + u.Username, storedPassword, u.MaxConnections, u.ExpiresAt, u.LimitMbpsUp, u.LimitMbpsDown, + u.DataQuotaBytes, normalizeQuotaAction(u.QuotaAction), quotaThrottleMbpsOrDefault(u.QuotaThrottleMbps), + u.TOTPSecret, u.TOTPPeriod, u.TOTPWindow, u.TOTPDigits, u.AllowStaticPassword, u.UsePAM, u.OwnerUsername) + return err +} + +func (s *Store) DeleteUser(ctx context.Context, username string) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM ssh_users WHERE username = $1`, username) + return err +} + +// ---------- Optional persistence for interface totals ---------- + +func (s *Store) EnsureIfaceTotalsTable(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS ssh_iface_totals ( + iface TEXT PRIMARY KEY, + total_rx_bytes BIGINT NOT NULL DEFAULT 0, + total_tx_bytes BIGINT NOT NULL DEFAULT 0, + last_kernel_rx_bytes BIGINT NOT NULL DEFAULT 0, + last_kernel_tx_bytes BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + reset_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS reset_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return nil +} + +func (s *Store) LoadIfaceTotals(ctx context.Context) ([]IfaceTotals, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT iface, total_rx_bytes, total_tx_bytes, last_kernel_rx_bytes, last_kernel_tx_bytes, updated_at, reset_at + FROM ssh_iface_totals + WHERE iface <> 'lo'`) + if err != nil { + return nil, err + } + defer rows.Close() + + out := []IfaceTotals{} + for rows.Next() { + var r IfaceTotals + var updated, resetAt time.Time + if err := rows.Scan(&r.Iface, &r.TotalRxBytes, &r.TotalTxBytes, &r.LastKernelRxBytes, &r.LastKernelTxBytes, &updated, &resetAt); err != nil { + return nil, err + } + r.UpdatedAt = updated + r.ResetAt = resetAt + out = append(out, r) + } + if err := rows.Err(); err != nil { + return nil, err + } + return out, nil +} + +func (s *Store) UpsertIfaceTotals(ctx context.Context, rows []IfaceTotals) error { + if len(rows) == 0 { + return nil + } + // Simple loop (small N: number of interfaces). Keeps CPU/DB overhead minimal. + for _, r := range rows { + if isIgnoredInterface(r.Iface) { + continue + } + resetAt := r.ResetAt + if resetAt.IsZero() { + resetAt = time.Now() + } + _, err := s.db.ExecContext(ctx, ` + INSERT INTO ssh_iface_totals (iface, total_rx_bytes, total_tx_bytes, last_kernel_rx_bytes, last_kernel_tx_bytes, updated_at, reset_at) + VALUES ($1, $2, $3, $4, $5, NOW(), $6) + ON CONFLICT (iface) DO UPDATE + SET total_rx_bytes = EXCLUDED.total_rx_bytes, + total_tx_bytes = EXCLUDED.total_tx_bytes, + last_kernel_rx_bytes = EXCLUDED.last_kernel_rx_bytes, + last_kernel_tx_bytes = EXCLUDED.last_kernel_tx_bytes, + updated_at = NOW(), + reset_at = EXCLUDED.reset_at`, + r.Iface, r.TotalRxBytes, r.TotalTxBytes, r.LastKernelRxBytes, r.LastKernelTxBytes, resetAt) + if err != nil { + return err + } + } + return nil +} + +func reloadUsersFromDB(ctx context.Context, store *Store) { + if store == nil { + return + } + users, err := store.LoadUsers(ctx) + if err != nil { + log.Printf("failed to reload users from db: %v", err) + return + } + userMgr.ReplaceAllPreserveRuntime(users) + updateUserDisplay() +} + +func startAdminAPI(store *Store, addr string) { + mux := http.NewServeMux() + + // Auth (no session required) + mux.Handle("/api/auth/login", http.HandlerFunc(handleLogin(store))) + + // Auth (session required) + mux.Handle("/api/auth/logout", sessionMiddleware(http.HandlerFunc(handleLogout))) + mux.Handle("/api/auth/me", sessionMiddleware(http.HandlerFunc(handleMe))) + + // SSH user management (session required; role-filtered inside handlers) + mux.Handle("/api/users", sessionMiddleware(http.HandlerFunc(handleListUsers))) + mux.Handle("/api/users/create", sessionMiddleware(http.HandlerFunc(handleCreateUser(store)))) + mux.Handle("/api/users/reset-traffic", sessionMiddleware(http.HandlerFunc(handleResetUserTraffic(store)))) + mux.Handle("/api/users/delete", sessionMiddleware(http.HandlerFunc(handleDeleteUser(store)))) + + // Server stats: visible to authenticated sessions; reset remains superadmin-only. + mux.Handle("/api/stats", sessionMiddleware(http.HandlerFunc(handleStats))) + mux.Handle("/api/stats/interfaces/reset", saSession(http.HandlerFunc(handleResetInterfaceStats(store)))) + mux.Handle("/api/vnstat", saSession(http.HandlerFunc(handleVnstat(store)))) + mux.Handle("/api/vnstat/reset", saSession(http.HandlerFunc(handleVnstatReset(store)))) + mux.Handle("/api/system/logs", saSession(http.HandlerFunc(handleSystemLogs))) + mux.Handle("/api/system/logs/reset", saSession(http.HandlerFunc(handleSystemLogsReset))) + mux.Handle("/api/system/update-status", saSession(http.HandlerFunc(handleUpdateStatus))) + mux.Handle("/api/dnstt", saSession(http.HandlerFunc(handleDnsttStats))) + mux.Handle("/api/dnstt/logs", saSession(http.HandlerFunc(handleDnsttLogs))) + mux.Handle("/api/bhttp", saSession(http.HandlerFunc(handleBHTTPStats))) + mux.Handle("/api/bhttp/logs", saSession(http.HandlerFunc(handleBHTTPLogs))) + mux.Handle("/api/btun", saSession(http.HandlerFunc(handleBTUNStats))) + mux.Handle("/api/btun/logs", saSession(http.HandlerFunc(handleBTUNLogs))) + mux.Handle("/api/hcr", saSession(http.HandlerFunc(handleHCRStats))) + mux.Handle("/api/hcr/logs", saSession(http.HandlerFunc(handleHCRLogs))) + + // Superadmin-only: reseller management + mux.Handle("/api/resellers", saSession(http.HandlerFunc(handleListResellers(store)))) + mux.Handle("/api/resellers/create", saSession(http.HandlerFunc(handleCreateReseller(store)))) + mux.Handle("/api/resellers/delete", saSession(http.HandlerFunc(handleDeleteReseller(store)))) + + // Master/slave server management. Superadmins can add slave nodes; all authenticated + // users can read the enabled server list to pick where accounts are created. + mux.Handle("/api/servers", sessionMiddleware(http.HandlerFunc(handleServers(store)))) + mux.Handle("/api/servers/test", saSession(http.HandlerFunc(handleServerTest(store)))) + mux.Handle("/api/servers/config", saSession(http.HandlerFunc(handleManagedServerConfig(store)))) + + // Xray-core management. Service/config/log actions are superadmin-only; + // authenticated resellers may list inbounds and manage their own Xray clients. + mux.Handle("/api/xray/status", sessionMiddleware(http.HandlerFunc(handleXrayStatus))) + mux.Handle("/api/xray/start", saSession(http.HandlerFunc(handleXrayStart))) + mux.Handle("/api/xray/stop", saSession(http.HandlerFunc(handleXrayStop))) + mux.Handle("/api/xray/restart", saSession(http.HandlerFunc(handleXrayRestart))) + mux.Handle("/api/xray/stats/repair", saSession(http.HandlerFunc(handleXrayRepairStats))) + mux.Handle("/api/xray/config", saSession(http.HandlerFunc(handleXrayConfig))) + mux.Handle("/api/xray/logs", saSession(http.HandlerFunc(handleXrayLogs))) + mux.Handle("/api/xray/inbounds", sessionMiddleware(http.HandlerFunc(handleXrayInbounds))) + mux.Handle("/api/xray/clients/add", sessionMiddleware(http.HandlerFunc(handleXrayClientAdd))) + mux.Handle("/api/xray/clients/update", sessionMiddleware(http.HandlerFunc(handleXrayClientUpdate))) + mux.Handle("/api/xray/clients/reset-traffic", sessionMiddleware(http.HandlerFunc(handleXrayClientResetTraffic))) + mux.Handle("/api/xray/clients/remove", sessionMiddleware(http.HandlerFunc(handleXrayClientRemove))) + + // Superadmin-only: TLS certificate generation + mux.Handle("/api/tls/generate-selfsigned", saSession(handleManagedProxyOrLocal(store, handleTLSGenerateSelfSigned))) + mux.Handle("/api/tls/letsencrypt", saSession(handleManagedProxyOrLocal(store, handleTLSLetsEncrypt))) + mux.Handle("/api/tls/upload-pem", saSession(handleManagedProxyOrLocal(store, handleTLSUploadPEM))) + mux.Handle("/api/tls/certs", saSession(handleManagedProxyOrLocal(store, handleTLSCertList))) + mux.Handle("/api/tls/certs/update", saSession(handleManagedProxyOrLocal(store, handleTLSCertUpdate))) + + // Superadmin-only: DNSTT key management + mux.Handle("/api/dnstt/genkey", saSession(handleManagedProxyOrLocal(store, handleDnsttGenKey))) + mux.Handle("/api/dnstt/pubkey", saSession(handleManagedProxyOrLocal(store, handleDnsttGetPubKey))) + + // Superadmin-only: server config (read/write config.json + live banner apply) + mux.Handle("/api/server/config", saSession(http.HandlerFunc(handleServerConfig))) + + // Superadmin-only: Telegram sales bot management + mux.Handle("/api/bot/config", saSession(http.HandlerFunc(handleBotConfig(store)))) + mux.Handle("/api/bot/plans", saSession(http.HandlerFunc(handleBotPlans(store)))) + mux.Handle("/api/bot/credit-packages", saSession(http.HandlerFunc(handleBotCreditPackages(store)))) + mux.Handle("/api/bot/users", saSession(http.HandlerFunc(handleBotUsers(store)))) + mux.Handle("/api/bot/transactions", saSession(http.HandlerFunc(handleBotTransactions(store)))) + mux.Handle("/api/bot/settings", saSession(http.HandlerFunc(handleBotSettings(store)))) + mux.Handle("/api/bot/test", saSession(http.HandlerFunc(handleBotTest(store)))) + + // Public: Mercado Pago payment webhook (validated by signature inside). + mux.Handle("/api/mp/webhook", http.HandlerFunc(handleMPWebhook)) + + // Public: user/UUID check — no auth, CORS *. + mux.Handle("/check", http.HandlerFunc(handleCheck)) + + go func() { + log.Printf("DragonCoreSSH API listening on %s", addr) + server := &http.Server{ + Addr: addr, + Handler: secureAPIHandler(mux), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 2 * time.Minute, + IdleTimeout: 90 * time.Second, + MaxHeaderBytes: 1 << 20, + } + if err := server.ListenAndServe(); err != nil { + log.Printf("admin http error: %v", err) + } + }() +} + +// UserDTO is returned by the admin API for listing. +type UserDTO struct { + Username string `json:"username"` + ActiveConns int `json:"active_conns"` + MaxConnections int `json:"max_connections"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + LimitUpMbps int `json:"limit_mbps_up"` + LimitDownMbps int `json:"limit_mbps_down"` + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + TotalUplinkBytes int64 `json:"total_uplink_bytes"` + TotalDownlinkBytes int64 `json:"total_downlink_bytes"` + TotalBytes int64 `json:"total_bytes"` + // Live account-wide speed in bytes per second, summed across every + // connection the user has open. + UpBytesPerSec float64 `json:"up_bytes_per_sec"` + DownBytesPerSec float64 `json:"down_bytes_per_sec"` + QuotaExceeded bool `json:"quota_exceeded"` + TOTPSecret string `json:"totp_secret,omitempty"` + TOTPPeriod int `json:"totp_period"` + TOTPWindow int `json:"totp_window"` + TOTPDigits int `json:"totp_digits"` + AllowStaticPassword bool `json:"allow_static_password"` + UsePAM bool `json:"use_pam"` + TOTPEnabled bool `json:"totp_enabled"` + OwnerUsername string `json:"owner_username,omitempty"` + ServerID string `json:"server_id,omitempty"` +} + +func handleListUsers(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + sess := sessionFromCtx(r.Context()) + filterOwner := "" + if sess != nil && sess.Role == RoleReseller { + filterOwner = sess.Username + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/users", nil, filterOwner) { + return + } + states := userMgr.List() + out := make([]UserDTO, 0, len(states)) + for _, u := range states { + u.mu.Lock() + c := len(u.conns) + u.btunConns + u.ActiveConns = c + cfg := u.Cfg + expires := u.ExpiresAt + u.mu.Unlock() + totalUp := atomic.LoadInt64(&u.TotalUplinkBytes) + totalDown := atomic.LoadInt64(&u.TotalDownlinkBytes) + totalBytes := atomic.LoadInt64(&u.totalBytes) + + // Resellers only see their own users + if sess != nil && sess.Role == RoleReseller && cfg.OwnerUsername != sess.Username { + continue + } + + rate := sshUserRate(cfg.Username) + + out = append(out, UserDTO{ + Username: cfg.Username, + ActiveConns: c, + MaxConnections: cfg.MaxConnections, + ExpiresAt: expires, + LimitUpMbps: cfg.LimitMbpsUp, + LimitDownMbps: cfg.LimitMbpsDown, + DataQuotaBytes: cfg.DataQuotaBytes, + QuotaAction: normalizeQuotaAction(cfg.QuotaAction), + QuotaThrottleMbps: quotaThrottleMbpsOrDefault(cfg.QuotaThrottleMbps), + TotalUplinkBytes: totalUp, + TotalDownlinkBytes: totalDown, + TotalBytes: totalBytes, + UpBytesPerSec: rate.UpBytesPerSec, + DownBytesPerSec: rate.DownBytesPerSec, + QuotaExceeded: cfg.DataQuotaBytes > 0 && totalBytes >= cfg.DataQuotaBytes, + TOTPSecret: cfg.TOTPSecret, + TOTPPeriod: cfg.TOTPPeriod, + TOTPWindow: cfg.TOTPWindow, + TOTPDigits: cfg.TOTPDigits, + AllowStaticPassword: cfg.AllowStaticPassword, + UsePAM: cfg.UsePAM, + TOTPEnabled: strings.TrimSpace(cfg.TOTPSecret) != "", + OwnerUsername: cfg.OwnerUsername, + }) + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(out) +} + +// NOTE: Password is pointer to distinguish "field missing" vs "field present". +type UserPayload struct { + Username string `json:"username"` + Password *string `json:"password,omitempty"` // nil or empty = keep existing if user already exists + MaxConnections int `json:"max_connections"` + ExpiresAt string `json:"expires_at"` + LimitUpMbps int `json:"limit_mbps_up"` + LimitDownMbps int `json:"limit_mbps_down"` + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + ResetUsage bool `json:"reset_usage,omitempty"` + TOTPSecret string `json:"totp_secret"` + TOTPPeriod int `json:"totp_period"` + TOTPWindow int `json:"totp_window"` + TOTPDigits int `json:"totp_digits"` + AllowStaticPassword bool `json:"allow_static_password"` + UsePAM bool `json:"use_pam"` + OwnerUsername string `json:"owner_username,omitempty"` + ServerID string `json:"server_id,omitempty"` +} + +func handleCreateUser(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + + var p UserPayload + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + p.Username = strings.TrimSpace(p.Username) + if p.Username == "" { + http.Error(w, "username required", http.StatusBadRequest) + return + } + if p.MaxConnections < 0 || p.MaxConnections > 10000 { + http.Error(w, "max_connections must be between 0 and 10000", http.StatusBadRequest) + return + } + if p.LimitUpMbps < 0 || p.LimitUpMbps > 1000000 || p.LimitDownMbps < 0 || p.LimitDownMbps > 1000000 { + http.Error(w, "bandwidth limits must be between 0 and 1000000 Mbps", http.StatusBadRequest) + return + } + if p.ExpiresAt != "" { + if _, err := time.Parse(time.RFC3339, p.ExpiresAt); err != nil { + http.Error(w, "invalid expires_at (RFC3339 required)", http.StatusBadRequest) + return + } + } + if err := validateQuotaConfig(p.DataQuotaBytes, p.QuotaAction, p.QuotaThrottleMbps); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + ctx := r.Context() + if ms, remote, err := managedServerFromID(ctx, store, p.ServerID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if !ms.EnableSSH { + http.Error(w, "SSH creation is disabled for this server", http.StatusForbidden) + return + } + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller { + currentOwner, exists, ownerErr := remoteSSHUserOwner(ctx, ms, p.Username) + if ownerErr != nil { + http.Error(w, "could not verify remote ownership", http.StatusBadGateway) + return + } + if exists && currentOwner != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + if !exists { + owner, ok := adminUsers.get(sess.Username) + used, quotaErr := countOwnedQuotaAcrossManagedServers(ctx, store, sess.Username) + if quotaErr != nil { + http.Error(w, "could not verify reseller quota", http.StatusBadGateway) + return + } + if ok && owner.MaxUsers > 0 && used >= owner.MaxUsers { + http.Error(w, fmt.Sprintf("user limit reached (%d)", owner.MaxUsers), http.StatusForbidden) + return + } + } + p.OwnerUsername = sess.Username + } + p.ServerID = "" + body, _ := json.Marshal(p) + status, data, ct, err := proxyManagedServer(ctx, ms, http.MethodPost, "/api/users/create", body, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + + sess := sessionFromCtx(ctx) + if sess != nil && sess.Role == RoleReseller { + var existingOwner string + err := store.db.QueryRowContext(ctx, `SELECT owner_username FROM ssh_users WHERE username=$1`, p.Username).Scan(&existingOwner) + if err != nil && err != sql.ErrNoRows { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + if err == nil && existingOwner != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + } + + // Decide what password to use: + // - if payload has non-empty password -> use it + // - else try to read existing password from DB + // - if user exists -> keep existing password + // - if not exists and TOTP is enabled -> allow blank password + // - otherwise reject (password required for new user) + var password string + + if p.Password != nil && *p.Password != "" { + password = *p.Password + } else { + var existing string + err := store.db.QueryRowContext(ctx, + `SELECT password FROM ssh_users WHERE username = $1`, + p.Username, + ).Scan(&existing) + + if err == sql.ErrNoRows { + // PAM users authenticate against the system account, so they + // need neither a panel password nor a TOTP secret. + if strings.TrimSpace(p.TOTPSecret) == "" && !p.UsePAM { + http.Error(w, "password or totp_secret required for new user", http.StatusBadRequest) + return + } + password = "" + } else if err != nil { + log.Printf("failed to load existing password for %s: %v", p.Username, err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } else { + password = existing + } + } + + // Determine owner and enforce reseller quota + ownerUsername := "" + if sess != nil && sess.Role == RoleReseller { + ownerUsername = sess.Username + // Enforce user limit — only count on new user creation + var existsInDB bool + _ = store.db.QueryRowContext(ctx, + `SELECT TRUE FROM ssh_users WHERE username=$1`, p.Username, + ).Scan(&existsInDB) + if !existsInDB { + owner, ok := adminUsers.get(sess.Username) + used, quotaErr := countOwnedQuotaAcrossManagedServers(ctx, store, sess.Username) + if quotaErr != nil { + http.Error(w, "could not verify reseller quota", http.StatusBadGateway) + return + } + if ok && owner.MaxUsers > 0 && used >= owner.MaxUsers { + http.Error(w, fmt.Sprintf("user limit reached (%d)", owner.MaxUsers), http.StatusForbidden) + return + } + } + } else if sess != nil && sess.Role == RoleSuperAdmin && strings.TrimSpace(p.OwnerUsername) != "" { + ownerUsername = strings.TrimSpace(p.OwnerUsername) + } + + cfg := UserConfig{ + Username: p.Username, + Password: password, + MaxConnections: p.MaxConnections, + ExpiresAt: p.ExpiresAt, + LimitMbpsUp: p.LimitUpMbps, + LimitMbpsDown: p.LimitDownMbps, + DataQuotaBytes: p.DataQuotaBytes, + QuotaAction: normalizeQuotaAction(p.QuotaAction), + QuotaThrottleMbps: quotaThrottleMbpsOrDefault(p.QuotaThrottleMbps), + TOTPSecret: strings.TrimSpace(p.TOTPSecret), + TOTPPeriod: p.TOTPPeriod, + TOTPWindow: p.TOTPWindow, + TOTPDigits: p.TOTPDigits, + AllowStaticPassword: p.AllowStaticPassword, + UsePAM: p.UsePAM, + OwnerUsername: ownerUsername, + } + + if err := store.UpsertUser(ctx, cfg); err != nil { + log.Printf("failed to upsert user: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + // Force-disconnect all active sessions for this user so new config applies. + userMgr.DisconnectUser(p.Username) + if p.ResetUsage { + if err := resetSSHUserTrafficAccounting(ctx, store, p.Username); err != nil { + http.Error(w, "could not reset usage", http.StatusInternalServerError) + return + } + } + + reloadUsersFromDB(ctx, store) + w.WriteHeader(http.StatusCreated) + } +} + +func handleResetUserTraffic(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + + var req struct { + Username string `json:"username"` + ServerID string `json:"server_id,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + req.Username = strings.TrimSpace(req.Username) + if req.Username == "" { + http.Error(w, "username required", http.StatusBadRequest) + return + } + + ctx := r.Context() + if ms, remote, err := managedServerFromID(ctx, store, req.ServerID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller && !remoteSSHUserOwned(ctx, ms, req.Username, sess.Username) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + req.ServerID = "" + body, _ := json.Marshal(req) + status, data, ct, err := proxyManagedServer(ctx, ms, http.MethodPost, "/api/users/reset-traffic", body, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + + var owner string + if err := store.db.QueryRowContext(ctx, `SELECT owner_username FROM ssh_users WHERE username=$1`, req.Username).Scan(&owner); err != nil { + if err == sql.ErrNoRows { + http.Error(w, "user not found", http.StatusNotFound) + } else { + http.Error(w, "db error", http.StatusInternalServerError) + } + return + } + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller && strings.TrimSpace(owner) != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + + if err := resetSSHUserTrafficAccounting(ctx, store, req.Username); err != nil { + log.Printf("failed to reset SSH traffic for %s: %v", req.Username, err) + http.Error(w, "could not reset traffic", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "username": req.Username}) + } +} + +func handleDeleteUser(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + + username := r.URL.Query().Get("username") + if username == "" { + http.Error(w, "username required", http.StatusBadRequest) + return + } + + ctx := r.Context() + if ms, remote, err := managedServerFromID(ctx, store, requestedServerID(r)); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller && !remoteSSHUserOwned(ctx, ms, username, sess.Username) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + remotePath := "/api/users/delete?username=" + url.QueryEscape(username) + status, data, ct, err := proxyManagedServer(ctx, ms, http.MethodDelete, remotePath, nil, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + + // Resellers may only delete their own users + sess := sessionFromCtx(ctx) + if sess != nil && sess.Role == RoleReseller { + u, ok := userMgr.Get(username) + if !ok || u.Cfg.OwnerUsername != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + } + + if err := store.DeleteUser(ctx, username); err != nil { + log.Printf("failed to delete user: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + + // Kick any live sessions for that user + userMgr.DisconnectUser(username) + + reloadUsersFromDB(ctx, store) + w.WriteHeader(http.StatusNoContent) + } +} + +// ---------- Stats API handler ---------- + +func handleStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/stats", nil, "") { + return + } + stats := getCurrentStats() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(stats) +} + +// handleDnsttStats returns the most recent DNSTT statistics snapshot. These +// counters represent activity in the last 5‑second window. The handler +// requires a GET request and is protected by the same bearer token as +// other admin API endpoints. +func handleDnsttStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/dnstt", nil, "") { + return + } + // Obtain a copy of the current snapshot. + stats := GetDNSTTStatsSnapshot() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(stats) +} + +// handleDnsttLogs returns the recent DNSTT log lines as a JSON array of strings. +// If DNSTT logging has not been initialised, it returns an empty array. The +// handler requires a GET request and uses the same bearer token as other +// admin endpoints. +func handleDnsttLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + lines := getDNSTTLogLines() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(lines) +} + +// handleBHTTPStats returns the current BHTTP transport counters. +func handleBHTTPStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/bhttp", nil, "") { + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(GetBHTTPStatsSnapshot()) +} + +// handleBHTTPLogs returns the recent BHTTP log lines as a JSON array. +func handleBHTTPLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + lines := getBHTTPLogLines() + if lines == nil { + lines = []string{} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(lines) +} + +// handleHCRStats returns the current HCR transport counters. +func handleHCRStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/hcr", nil, "") { + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(GetHCRStatsSnapshot()) +} + +// handleHCRLogs returns the recent HCR log lines as a JSON array. +func handleHCRLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + lines := getHCRLogLines() + if lines == nil { + lines = []string{} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(lines) +} + +// handleBTUNStats returns the current BTUN protocol server counters. +func handleBTUNStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/btun", nil, "") { + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(GetBTUNStatsSnapshot()) +} + +// handleBTUNLogs returns the recent BTUN log lines as a JSON array. +func handleBTUNLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + lines := getBTUNLogLines() + if lines == nil { + lines = []string{} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(lines) +} + +// ---------- Auth helpers ---------- + +func normalizeBase32Secret(secret string) string { + secret = strings.ToUpper(strings.TrimSpace(secret)) + secret = strings.ReplaceAll(secret, " ", "") + return secret +} + +func totpDigitsOrDefault(n int) int { + if n < 6 || n > 8 { + return 6 + } + return n +} + +func totpPeriodOrDefault(n int) int64 { + if n <= 0 { + return 60 + } + return int64(n) +} + +func totpWindowOrDefault(n int) int { + if n < 0 { + return 0 + } + if n == 0 { + return 1 + } + return n +} + +func pow10(n int) uint32 { + v := uint32(1) + for i := 0; i < n; i++ { + v *= 10 + } + return v +} + +func generateTOTPCode(secret string, ts time.Time, period int64, digits int) (string, error) { + secret = normalizeBase32Secret(secret) + key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) + if err != nil { + return "", fmt.Errorf("decode TOTP secret: %w", err) + } + counter := uint64(ts.Unix() / period) + var buf [8]byte + binary.BigEndian.PutUint64(buf[:], counter) + h := hmac.New(sha1.New, key) + _, _ = h.Write(buf[:]) + sum := h.Sum(nil) + offset := sum[len(sum)-1] & 0x0f + code := (uint32(sum[offset])&0x7f)<<24 | + uint32(sum[offset+1])<<16 | + uint32(sum[offset+2])<<8 | + uint32(sum[offset+3]) + mod := pow10(digits) + return fmt.Sprintf("%0*d", digits, code%mod), nil +} + +func matchTOTPPassword(u *UserState, supplied string, now time.Time) bool { + secret := strings.TrimSpace(u.Cfg.TOTPSecret) + if secret == "" { + return false + } + period := totpPeriodOrDefault(u.Cfg.TOTPPeriod) + digits := totpDigitsOrDefault(u.Cfg.TOTPDigits) + window := totpWindowOrDefault(u.Cfg.TOTPWindow) + for i := -window; i <= window; i++ { + stepTime := now.Add(time.Duration(i) * time.Duration(period) * time.Second) + code, err := generateTOTPCode(secret, stepTime, period, digits) + if err != nil { + log.Printf("user %s has invalid TOTP configuration: %v", u.Cfg.Username, err) + return false + } + if supplied == code { + return true + } + } + return false +} + +// ---------- Auth callbacks ---------- + +func passwordCallback(meta ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { + supplied := string(pass) + u, ok := userMgr.Get(meta.User()) + now := time.Now() + + // Enforce panel policy (expiry / reseller owner) for known users up front, + // so neither PAM nor the static password can bypass it. + if ok { + if u.ExpiresAt != nil && now.After(*u.ExpiresAt) { + log.Printf("user %s tried to connect but account is expired", meta.User()) + return nil, fmt.Errorf("account expired") + } + if sshUserQuotaBlocked(u) { + log.Printf("user %s tried to connect after reaching the data quota", meta.User()) + return nil, errDataQuotaExceeded + } + if err := ownerIsActive(u.Cfg.OwnerUsername); err != nil { + return nil, fmt.Errorf("authentication failed: %w", err) + } + } + + // System (PAM) login. When enabled server-wide, the Linux system password + // (/etc/shadow) is accepted for any regular account (UID >= 1000) — whether + // or not it is already a panel user. Unknown accounts are auto-imported on + // success. Falls through to panel credentials if PAM does not accept. + if isPAMAuthEnabled() { + if isRegularLoginUser(meta.User()) { + if err := authenticatePAM(meta.User(), supplied); err == nil { + if !ok { + importPAMUser(meta.User()) + } + pamLogf("PAM: %q authenticated against /etc/shadow", meta.User()) + return nil, nil + } else { + pamLogf("PAM: %q rejected by /etc/shadow: %v", meta.User(), err) + } + } else if !ok { + pamLogf("PAM: %q is not a regular login account (needs an /etc/passwd entry with UID >= %d)", meta.User(), minLoginUID) + } + } + + if !ok { + pamLogf("auth: user %q rejected (no panel account and PAM did not accept it)", meta.User()) + return nil, fmt.Errorf("authentication failed") + } + + // Fall back to panel-managed credentials (TOTP and/or static password). + if strings.TrimSpace(u.Cfg.TOTPSecret) != "" { + if matchTOTPPassword(u, supplied, now) { + return nil, nil + } + if u.Cfg.AllowStaticPassword && u.Cfg.Password == supplied { + return nil, nil + } + return nil, fmt.Errorf("authentication failed") + } + if u.Cfg.Password != supplied { + return nil, fmt.Errorf("authentication failed") + } + return nil, nil +} + +func publicKeyCallback(meta ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + u, ok := userMgr.Get(meta.User()) + if !ok { + return nil, fmt.Errorf("authentication failed") + } + if u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt) { + log.Printf("user %s tried to connect but account is expired", meta.User()) + return nil, fmt.Errorf("account expired") + } + if sshUserQuotaBlocked(u) { + return nil, errDataQuotaExceeded + } + if err := ownerIsActive(u.Cfg.OwnerUsername); err != nil { + return nil, fmt.Errorf("authentication failed: %w", err) + } + if u.PubKey == nil { + return nil, fmt.Errorf("no public key configured") + } + if !publicKeysEqual(u.PubKey, key) { + return nil, fmt.Errorf("authentication failed") + } + return nil, nil +} + +// ---------- Connection handling ---------- + +func handleConn(tcpConn net.Conn, config *ssh.ServerConfig) { + trackedConn := newActivityConn(tcpConn) + defer trackedConn.Close() + + // Global connection cap: reject before the expensive SSH handshake so a + // surge past normal load cannot exhaust memory/CPU. Count first, then check, + // so the defer always balances the increment. + live := atomic.AddInt64(&activeSSHConns, 1) + defer atomic.AddInt64(&activeSSHConns, -1) + if lim := atomic.LoadInt64(&maxTotalConns); lim > 0 && live > lim { + r := atomic.AddInt64(&sshConnsRejected, 1) + if r == 1 || r%1000 == 0 { + log.Printf("ssh: global connection cap reached (%d); rejected %d connection(s) so far", lim, r) + } + return + } + + // Prevent goroutine leaks from clients that connect but never complete the SSH handshake. + _ = trackedConn.SetReadDeadline(time.Now().Add(sshHandshakeTimeout)) + + sshConn, chans, reqs, err := ssh.NewServerConn(trackedConn, config) + if err != nil { + log.Println("ssh handshake failed:", err) + return + } + // Clear deadlines after a successful handshake. Runtime cleanup is handled + // by monitorSSHIdle, which checks traffic in both directions. + _ = trackedConn.SetDeadline(time.Time{}) + username := sshConn.User() + log.Printf("new SSH connection from %s as %s", sshConn.RemoteAddr(), username) + + u, ok := userMgr.Get(username) + if !ok { + log.Printf("user %s not found in config (should not happen if auth is correct)", username) + sshConn.Close() + return + } + + // Track active connection and enforce max_connections. The connection map is + // treated as the source of truth so stale counters can self-heal. + u.mu.Lock() + if u.conns == nil { + u.conns = make(map[*ssh.ServerConn]struct{}) + } + // BTUN sessions count against the same allowance, so a user cannot double + // their limit by mixing transports. + activeConns := len(u.conns) + u.btunConns + u.ActiveConns = activeConns + if u.Cfg.MaxConnections > 0 && activeConns >= u.Cfg.MaxConnections { + u.mu.Unlock() + log.Printf("user %s exceeded max_connections (%d)", username, u.Cfg.MaxConnections) + sshConn.Close() + return + } + u.conns[sshConn] = struct{}{} + u.ActiveConns = len(u.conns) + u.btunConns + u.mu.Unlock() + + // Use per-user limit if set; otherwise fall back to the global config default. + limitUp, limitDown := u.Cfg.LimitMbpsUp, u.Cfg.LimitMbpsDown + if limitUp == 0 || limitDown == 0 { + defUp, defDown := getDefaultLimits() + if limitUp == 0 { + limitUp = defUp + } + if limitDown == 0 { + limitDown = defDown + } + } + var upLimiter, downLimiter *rate.Limiter + if limitUp > 0 { + bps := mbpsToBytesPerSec(limitUp) + upLimiter = rate.NewLimiter(rate.Limit(bps), int(bps)) + } + if limitDown > 0 { + bps := mbpsToBytesPerSec(limitDown) + downLimiter = rate.NewLimiter(rate.Limit(bps), int(bps)) + } + + updateUserDisplay() + + idleDone := make(chan struct{}) + if idleTimeout := getSSHIdleTimeout(); idleTimeout > 0 { + go monitorSSHIdle(trackedConn, sshConn, username, idleTimeout, idleDone) + } + + defer func() { + close(idleDone) + u.mu.Lock() + delete(u.conns, sshConn) + u.ActiveConns = len(u.conns) + u.btunConns + u.mu.Unlock() + + updateUserDisplay() + sshConn.Close() + }() + + go ssh.DiscardRequests(reqs) + + for newChan := range chans { + switch newChan.ChannelType() { + case "direct-tcpip": + go handleDirectTCPIP(newChan, u, upLimiter, downLimiter) + case "session": + go handleDummySession(newChan) + default: + newChan.Reject(ssh.UnknownChannelType, "unsupported channel type") + } + } +} + +type directTCPIPReq struct { + Host string + Port uint32 + OriginAddr string + OriginPort uint32 +} + +func handleDirectTCPIP(newChan ssh.NewChannel, u *UserState, upLimiter, downLimiter *rate.Limiter) { + if sshUserQuotaBlocked(u) { + newChan.Reject(ssh.Prohibited, "data quota exceeded") + return + } + var req directTCPIPReq + if err := ssh.Unmarshal(newChan.ExtraData(), &req); err != nil { + newChan.Reject(ssh.Prohibited, "bad direct-tcpip request") + return + } + + target := net.JoinHostPort(req.Host, strconv.FormatUint(uint64(req.Port), 10)) + log.Printf("direct-tcpip: user=%s connecting to %s from %s:%d", + u.Cfg.Username, target, req.OriginAddr, req.OriginPort) + + dialer := &net.Dialer{Timeout: directTCPIPDialTimeout, KeepAlive: 30 * time.Second} + backend, err := dialer.Dial("tcp", target) + if err != nil { + log.Printf("failed to connect to %s: %v", target, err) + newChan.Reject(ssh.ConnectionFailed, err.Error()) + return + } + + ch, reqs, err := newChan.Accept() + if err != nil { + _ = backend.Close() + return + } + + // Shared closer: when either copy direction finishes (including a + // half-close that never completes), both sides are force-closed so the + // other direction unblocks. Close is idempotent, so calling it from both + // directions is safe and no separate waiter goroutine is needed. + ctx, cancel := context.WithCancel(context.Background()) + var closeOnce sync.Once + closeAll := func() { + closeOnce.Do(func() { + cancel() + _ = backend.Close() + _ = ch.Close() + }) + } + + // Drain channel requests concurrently so the peer isn't left waiting. + go func() { + for req := range reqs { + if req.WantReply { + req.Reply(false, nil) + } + } + }() + + // upstream: SSH channel -> backend, in its own goroutine. + go func() { + _, _ = copyWithRateLimitContext(ctx, sshQuotaWriter{w: backend, user: u, uplink: true, ctx: ctx}, ch, upLimiter) + // Signal to the backend that we are done writing. + if cw, ok := backend.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + closeAll() + }() + + // downstream: backend -> SSH channel, run in this goroutine. + // handleDirectTCPIP already runs as its own goroutine (see handleConn), + // so reusing it here avoids spawning a third goroutine per channel. + _, _ = copyWithRateLimitContext(ctx, sshQuotaWriter{w: ch, user: u, uplink: false, ctx: ctx}, backend, downLimiter) + closeAll() +} + +func handleDummySession(newChan ssh.NewChannel) { + ch, reqs, err := newChan.Accept() + if err != nil { + return + } + + go func() { + defer ch.Close() + for req := range reqs { + if req.WantReply { + req.Reply(false, nil) + } + } + }() +} + +// ---------- UI / display ---------- + +func updateUserDisplay() { + if !userCountEnabled { + return + } + + userStates := userMgr.List() + parts := make([]string, 0, len(userStates)) + for _, u := range userStates { + u.mu.Lock() + c := len(u.conns) + u.btunConns + u.ActiveConns = c + name := u.Cfg.Username + u.mu.Unlock() + parts = append(parts, fmt.Sprintf("%s: %d", name, c)) + } + + sort.Strings(parts) + line := strings.Join(parts, " ") + if line == "" { + line = "no users" + } + + displayMu.Lock() + defer displayMu.Unlock() + + if len(line) < lastDisplayLen { + line = line + strings.Repeat(" ", lastDisplayLen-len(line)) + } + lastDisplayLen = len(line) + + fmt.Printf("\r%s", line) +} + +// ---------- Main ---------- + +// ======================== +// Port-80 HTTP-clean + SSH +// ======================== + +// bufferedConn is a net.Conn wrapper whose Read() is served by a bufio.Reader. +// This preserves any bytes already buffered/peeked during HTTP cleanup. +type bufferedConn struct { + net.Conn + r *bufio.Reader +} + +func (c *bufferedConn) Read(p []byte) (int, error) { return c.r.Read(p) } + +// handleHTTP80Conn applies the same "HTTP injection cleanup" that proxy.go did, +// then hands the cleaned connection directly to the SSH server handler, avoiding +// the extra io.Copy hop to a separate backend SSH process. +func handleHTTP80Conn(raw net.Conn, sshConfig *ssh.ServerConfig) { + // Best-effort TCP tuning (no hard dependency on TCPConn) + if tc, ok := raw.(*net.TCPConn); ok { + _ = tc.SetKeepAlive(true) + _ = tc.SetKeepAlivePeriod(30 * time.Second) + _ = tc.SetNoDelay(true) + } + + // 101 response up-front (keeps behavior identical to the old proxy) + status := "Switching Protocols" + _, _ = raw.Write([]byte(fmt.Sprintf("HTTP/1.1 101 %s\r\n\r\n", status))) + + skip200 := false + br := bufio.NewReaderSize(raw, 4<<10) + + // Drain chained HTTP header blocks with a short rolling deadline so Peek/ReadBytes never stalls. + cleanWindow := 30 * time.Second + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + + for { + // swallow stray CR/LF between chained blocks + if skipped, _ := eatLeadingEOL(br); skipped > 0 { + log.Printf("[CLEAN] skipped %d EOL bytes between blocks", skipped) + } + + if lit, _ := eatLiteralBackslashCRLF(br); lit > 0 { + log.Printf("[CLEAN] skipped %d bytes of literal \"\\r\\n\"", lit) + // keep rolling the deadline since we consumed data + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + // continue to try cleaning more + continue + } + if litN, _ := eatLiteralBackslashLF(br); litN > 0 { + log.Printf("[CLEAN] skipped %d bytes of literal \"\\n\"", litN) + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + continue + } + + // peek a bit more so we can classify reliably + size := 8 + if b := br.Buffered(); b > 0 && b < size { + size = b + } + if size < 1 { + size = 1 + } + + peek, err := br.Peek(size) + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Timeout() { + log.Printf("[CLEAN] timeout; pass-through next=%s", peekPreview(br, 64)) + break + } + if err == io.EOF { + // Normal when payload stops. Proceed. + log.Printf("[CLEAN] EOF; nothing left") + break + } + log.Println("[CLEAN] peek error:", err) + break + } + + // Fast path: HTTP-ish at offset 0 (request-line OR status-line) + if maybeHTTPStartPrefix(peek) { + firstLine, headers, err := discardAndCaptureHTTP(br) + if err != nil { + log.Println("[CLEAN] discard error:", err) + break + } + if headerHasValue(headers, "npv-x", "ok") { + cleanWindow = 2 * time.Second + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + skip200 = true + status = "OK" + _, err = raw.Write([]byte(fmt.Sprintf("HTTP/1.1 200 %s\r\n\r\n", status))) + if err != nil { + log.Println("Failed to write 200 OK:", err) + return + } + log.Printf("[CLEAN] NPV-X: OK; promote clean window to %s", cleanWindow) + } + if bytes.Contains(bytes.ToLower(headers), []byte("x-skip: 200")) { + skip200 = true + log.Printf("[CLEAN] detected and stripped X-Skip: 200 header") + } + log.Printf("[CLEAN] discarded HTTP block: %q", firstLine) + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + continue + } + + // Slow path: scan the already-buffered bytes for a later HTTP token + if bufN := br.Buffered(); bufN > 0 { + pbuf, _ := br.Peek(bufN) + + // If we see SSH banner soon, stop cleaning now + if iSSH := bytes.Index(pbuf, []byte("SSH-")); iSSH >= 0 && iSSH < 64 { + log.Printf("[CLEAN] SSH banner detected at +%d; stop cleaning", iSSH) + log.Printf("[CLEAN] pass-through begins; next=%s", peekPreview(br, 64)) + break + } + + if pos := findHTTPStartIndex(pbuf); pos > 0 { + // 1) discard junk prefix before the HTTP token + noise := make([]byte, pos) + if _, err := io.ReadFull(br, noise); err != nil { + log.Printf("[CLEAN] error discarding noise prefix: %v", err) + break + } + log.Printf("[CLEAN] discarded NOISE prefix (%d bytes): %q (hex:%s)", + pos, asciiPreview(noise, 64), hexPreview(noise, 64)) + + // 2) discard the HTTP block starting at current position + firstLine, err := discardOneHTTP(br) + if err != nil { + log.Printf("[CLEAN] discard error after noise: %v", err) + break + } + log.Printf("[CLEAN] discarded HTTP block after noise: %q", firstLine) + _ = raw.SetReadDeadline(time.Now().Add(cleanWindow)) + continue + } + + // No HTTP tokens; pass-through whatever remains + log.Printf("[CLEAN] pass-through begins; next=%s", peekPreview(br, 64)) + } else { + log.Printf("[CLEAN] pass-through (no buffered data)") + } + break + } + + if skip200 { + log.Printf("[SKIP] X-Skip: 200 detected earlier; not sending 200 OK") + } else { + status = "OK" + _, err := raw.Write([]byte(fmt.Sprintf("HTTP/1.1 200 %s\r\n\r\n", status))) + if err != nil { + log.Println("Failed to write 200 OK:", err) + return + } + } + + // Clear deadline before SSH handshake begins. + _ = raw.SetReadDeadline(time.Time{}) + + // A tunnel client may use an HTTP request as cover, exactly like the + // injection clients this cleanup exists for. The cleanup above consumed + // that cover and already answered 101/200, so what remains is either the + // SSH banner or a tunnel handshake; only the latter is handed over. + if tunnelShareEnabled() { + reader, taken := tunnelTakeSharedConn(raw, br) + if taken { + return + } + br = reader + } + + // Hand off to SSH server, ensuring any buffered bytes are preserved. + handleConn(&bufferedConn{Conn: raw, r: br}, sshConfig) +} + +// serveHTTP80 accepts connections on ln and dispatches each to +// handleHTTP80Conn. It logs accept errors but otherwise runs +// indefinitely. This helper is used to support multiple listen +// addresses without duplicating accept loop code. +func serveHTTP80(ln net.Listener) { + for { + tcpConn, err := ln.Accept() + if err != nil { + if isListenerClosed(err) { + return + } + log.Printf("accept error on %s: %v", ln.Addr().String(), err) + continue + } + go handleProxyConn(tcpConn, getSSHConfig()) + } +} + +// handleProxyConn owns one connection accepted on a public proxy port. When +// BHTTP shares these ports it gets first look, because a BHTTP client speaks +// immediately and must not receive the unsolicited "HTTP/1.1 101" that the +// HTTP-injection path opens with. Anything that is not a BHTTP frame falls +// through to handleHTTP80Conn with its bytes untouched. +func handleProxyConn(raw net.Conn, sshConfig *ssh.ServerConfig) { + // Best-effort TCP tuning here too: the sniff may wrap the connection, and + // handleHTTP80Conn's own type assertion would then no longer see a TCPConn. + if tc, ok := raw.(*net.TCPConn); ok { + _ = tc.SetKeepAlive(true) + _ = tc.SetKeepAlivePeriod(30 * time.Second) + _ = tc.SetNoDelay(true) + } + if !tunnelShareEnabled() && !nativeSharedEnabled() { + handleHTTP80Conn(raw, sshConfig) + return + } + reader, taken := tunnelTakeSharedConn(raw, nil) + if taken { + return + } + reader, taken = nativeTakeSharedConn(raw, reader) + if taken { return } + handleHTTP80Conn(&bufferedConn{Conn: raw, r: reader}, sshConfig) +} + +// serveRawSSH accepts connections on ln and passes each directly into +// handleConn. Unlike serveHTTP80 it does not perform HTTP cleanup +// and starts the SSH handshake immediately. This is used by local proxy and +// tunnel daemons that need a stable SSH upstream. +func serveRawSSH(ln net.Listener) { + for { + c, err := ln.Accept() + if err != nil { + if isListenerClosed(err) { + return + } + log.Printf("local accept error on %s: %v", ln.Addr().String(), err) + continue + } + go handleConn(c, getSSHConfig()) + } +} + +// serveTLSSSH accepts TLS-wrapped connections on ln. It forces a +// TLS handshake on each accepted connection so handshake failures are +// surfaced early, then passes the decrypted stream to handleConn. +// There is no backend dial or data copying; the SSH handler runs +// directly on the TLS stream. +func serveTLSSSH(ln net.Listener) { + for { + c, err := ln.Accept() + if err != nil { + if isListenerClosed(err) { + return + } + log.Printf("tls accept error on %s: %v", ln.Addr().String(), err) + continue + } + go func(client net.Conn) { + _ = client.SetDeadline(time.Now().Add(tlsHandshakeTimeout)) + if tc, ok := client.(*tls.Conn); ok { + if err := tc.Handshake(); err != nil { + log.Printf("tls handshake error from %s: %v", client.RemoteAddr().String(), err) + _ = client.Close() + return + } + } + _ = client.SetDeadline(time.Time{}) + if nativeSharedEnabled() { + reader, taken := nativeTakeSharedConn(client, nil) + if taken { return } + client = &bufferedConn{Conn: client, r: reader} + } + // Inside TLS the stream is either the SSH banner or, when a tunnel + // transport shares this port, its handshake. The sniff decides on + // the decrypted bytes, so the TLS certificate and SNI are untouched. + if tunnelShareEnabled() { + reader, taken := tunnelTakeSharedConn(client, nil) + if taken { + return + } + handleConn(&bufferedConn{Conn: client, r: reader}, getSSHConfig()) + return + } + handleConn(client, getSSHConfig()) + }(c) + } +} + +var httpMethods = [][]byte{ + // HTTP/1.1 + PATCH + []byte("GET "), []byte("HEAD "), []byte("POST "), []byte("PUT "), + []byte("DELETE "), []byte("CONNECT "), []byte("OPTIONS "), []byte("TRACE "), + []byte("PATCH "), + + // WebDAV (RFC 4918) + []byte("PROPFIND "), []byte("PROPPATCH "), []byte("MKCOL "), + []byte("COPY "), []byte("MOVE "), []byte("LOCK "), []byte("UNLOCK "), + + // WebDAV SEARCH (RFC 5323) + []byte("SEARCH "), + + // WebDAV ACL (RFC 3744) + []byte("ACL "), + + // WebDAV Versioning/DeltaV (RFC 3253) + []byte("VERSION-CONTROL "), []byte("REPORT "), []byte("CHECKOUT "), + []byte("CHECKIN "), []byte("UNCHECKOUT "), []byte("MKWORKSPACE "), + []byte("UPDATE "), []byte("LABEL "), []byte("MERGE "), + []byte("BASELINE-CONTROL "), []byte("MKACTIVITY "), + + // WebDAV Ordering (RFC 3648) + []byte("ORDERPATCH "), + + // WebDAV Bindings (RFC 5842) + []byte("BIND "), []byte("UNBIND "), []byte("REBIND "), + + // CalDAV (RFC 4791) + []byte("MKCALENDAR "), + + []byte("x-skip: "), + []byte("npv-x: "), +} + +func eatLeadingEOL(br *bufio.Reader) (int, error) { + n := 0 + for { + b, err := br.Peek(1) + if err != nil { + return n, err + } + if b[0] != '\r' && b[0] != '\n' { + return n, nil + } + if _, err := br.ReadByte(); err != nil { + return n, err + } + n++ + } +} + +func asciiPreview(b []byte, max int) string { + if len(b) > max { + b = b[:max] + } + out := make([]byte, len(b)) + for i, c := range b { + if c < 32 || c == 127 { + out[i] = '.' + } else { + out[i] = c + } + } + return string(out) +} + +func peekPreview(br *bufio.Reader, max int) string { + n := br.Buffered() + if n < 1 { + n = max + } + if n > max { + n = max + } + p, _ := br.Peek(n) + return fmt.Sprintf("%q (hex:% X)", asciiPreview(p, n), p) +} + +func httpStartTokens() [][]byte { + toks := [][]byte{ + []byte("HTTP/"), []byte("HTTP/1."), []byte("HTTP/2"), []byte("HTTP/3"), + []byte("PRI "), []byte("ICY "), + } + toks = append(toks, httpMethods...) + toks = append(toks, []byte("CONNECT")) // bare + return toks +} + +func findHTTPStartIndex(b []byte) int { + if len(b) == 0 { + return -1 + } + upper := bytes.ToUpper(b) + min := -1 + for _, t := range httpStartTokens() { + tu := bytes.ToUpper(t) + if idx := bytes.Index(upper, tu); idx >= 0 { + if min == -1 || idx < min { + min = idx + } + } + } + return min +} + +func hexPreview(b []byte, max int) string { + if len(b) > max { + b = b[:max] + } + return fmt.Sprintf("% X", b) +} + +func eatLiteralBackslashCRLF(br *bufio.Reader) (int, error) { + count := 0 + for { + p, err := br.Peek(4) + if err != nil { + // If fewer than 4 bytes buffered, nothing more to eat. + return count, nil + } + if len(p) >= 4 && p[0] == '\\' && p[1] == 'r' && p[2] == '\\' && p[3] == 'n' { + if _, err := br.Discard(4); err != nil { + return count, err + } + count += 4 + continue + } + return count, nil + } +} + +func eatLiteralBackslashLF(br *bufio.Reader) (int, error) { + p, err := br.Peek(2) + if err != nil || len(p) < 2 { + return 0, nil + } + if p[0] == '\\' && p[1] == 'n' { + if _, err := br.Discard(2); err != nil { + return 0, err + } + return 2, nil + } + return 0, nil +} + +func headerHasValue(headers []byte, key, want string) bool { + lh := bytes.ToLower(headers) + keyb := []byte(strings.ToLower(key)) + wantb := []byte(strings.ToLower(want)) + + // find ":" (allow spaces before colon too) + i := bytes.Index(lh, keyb) + for i >= 0 { + rest := lh[i+len(keyb):] + rest = bytes.TrimLeft(rest, " \t") + if len(rest) > 0 && rest[0] == ':' { + // slice to end-of-line + line := rest[1:] + if j := bytes.IndexByte(line, '\n'); j >= 0 { + line = line[:j] + } + line = bytes.TrimSpace(bytes.TrimSuffix(line, []byte{'\r'})) + return bytes.Equal(line, wantb) + } + // keep searching (avoid false positives on substrings) + next := lh[i+len(keyb):] + j := bytes.Index(next, keyb) + if j < 0 { + return false + } + i += len(keyb) + j + } + return false +} + +func discardAndCaptureHTTP(br *bufio.Reader) (string, []byte, error) { + const hardCap = 64 << 10 // 64 KiB + var buf bytes.Buffer + total := 0 + + first, err := br.ReadSlice('\n') + if err != nil { + return "", nil, err + } + buf.Write(first) + total += len(first) + if total > hardCap { + return "", nil, fmt.Errorf("http header too large") + } + + for { + line, err := br.ReadSlice('\n') + if err != nil { + return "", nil, err + } + total += len(line) + if total > hardCap { + return "", nil, fmt.Errorf("http header too large") + } + buf.Write(line) + if (len(line) == 1 && line[0] == '\n') || + (len(line) == 2 && line[0] == '\r' && line[1] == '\n') { + break + } + } + fl := strings.TrimRight(string(first), "\r\n") + return fl, buf.Bytes(), nil +} + +func discardOneHTTP(br *bufio.Reader) (string, error) { + const hardCap = 64 << 10 // 64 KiB + total := 0 + + // capture first line for printing + first, err := br.ReadSlice('\n') + if err != nil { + return "", err + } + total += len(first) + if total > hardCap { + return "", fmt.Errorf("http header too large") + } + + for { + line, err := br.ReadSlice('\n') + if err != nil { + return "", err + } + total += len(line) + if total > hardCap { + return "", fmt.Errorf("http header too large") + } + + // End of headers: "\n" or "\r\n" + if (len(line) == 1 && line[0] == '\n') || + (len(line) == 2 && line[0] == '\r' && line[1] == '\n') { + break + } + } + // Trim trailing CR/LF for nicer logs + fl := strings.TrimRight(string(first), "\r\n") + return fl, nil +} + +func maybeHTTPStartPrefix(b []byte) bool { + u := bytes.ToUpper(b) + + // Helper: partial prefix match + startsWithPartial := func(s string) bool { + su := []byte(s) + if len(u) <= len(su) { + return bytes.Equal(u, su[:len(u)]) + } + return bytes.HasPrefix(u, su) + } + + // Status-lines / prefaces (allow partial) + if startsWithPartial("HTTP/") || startsWithPartial("HTTP/1.") || + startsWithPartial("HTTP/2") || startsWithPartial("HTTP/3") || + startsWithPartial("PRI ") || startsWithPartial("ICY ") { + return true + } + + // Request-lines (methods) with partial match + for _, m := range httpMethods { + um := bytes.ToUpper(m) + if len(u) <= len(um) && bytes.Equal(u, um[:len(u)]) { // partial ok + return true + } + if len(u) >= len(um) && bytes.HasPrefix(u, um) { + return true + } + } + return false +} + +func main() { + if memTotal, _, err := readMemInfo(); err == nil && memTotal > 0 { + limit := int64(memTotal) * 80 / 100 + debug.SetMemoryLimit(limit) + log.Printf("GOMEMLIMIT auto-set to 80%% of RAM: %d MB", limit/1024/1024) + } + + configPath := flag.String("config", "", "path to JSON config file (default: ./config.json if present, otherwise /opt/sshpanel/config.json)") + quietFlag := flag.Bool("quiet", false, "override config and disable logs") + userCountFlag := flag.Bool("usercount", false, "show per-user connection counters (single line)") + hashAdminPasswordStdin := flag.Bool("hash-admin-password-stdin", false, "read an admin password from stdin and print a bcrypt hash") + flag.Parse() + if *hashAdminPasswordStdin { + password, readErr := io.ReadAll(io.LimitReader(os.Stdin, 1025)) + if readErr != nil { + log.Fatalf("read admin password: %v", readErr) + } + if err := validateAdminPassword(string(password)); err != nil { + log.Fatal(err) + } + hash, hashErr := hashAdminPassword(string(password)) + if hashErr != nil { + log.Fatal(hashErr) + } + fmt.Println(hash) + return + } + + resolvedConfigPath := resolveMainConfigPath(*configPath) + cfg, userMap, err := loadConfig(resolvedConfigPath) + if err != nil { + log.Fatalf("failed to load config: %v", err) + } + userMgr.ReplaceAll(userMap) + + // Store config path and live config for hot-reload via admin API. + globalCfgPath = resolvedConfigPath + setGlobalCfg(cfg) + + userCountEnabled = cfg.UserCount || *userCountFlag + + var store *Store + pgDSN := os.Getenv("PG_DSN") + if pgDSN != "" { + store, err = NewStore(pgDSN) + if err != nil { + log.Fatalf("failed to connect to postgres: %v", err) + } + + ctx := context.Background() + dbUsers, err := store.LoadUsers(ctx) + if err != nil { + log.Fatalf("failed to load users from database: %v", err) + } + if len(dbUsers) > 0 { + userMgr.ReplaceAll(dbUsers) + } + } + + // Bootstrap admin users and reseller expiry checker. + if store != nil { + ctx := context.Background() + if pw, err := store.BootstrapSuperAdmin(ctx); err != nil { + log.Printf("failed to bootstrap superadmin: %v", err) + } else if pw != "" { + log.Printf("=== FIRST RUN: superadmin created — username: admin password: %s ===", pw) + } + if err := loadAdminUsersIntoCache(ctx, store); err != nil { + log.Printf("failed to load admin users: %v", err) + } + startResellerExpiryChecker(store) + // Start the Telegram sales bot if enabled in the DB config. + startBotService(store) + } + + // Optional: initialize interface totals persistence (best-effort). + if store != nil { + statsStore = store + startSSHUserTrafficFlusher(store) + ctx := context.Background() + if err := store.EnsureXrayClientsSchema(ctx); err != nil { + log.Printf("xray clients table: %v", err) + } else { + if err := store.ResetXrayActiveConnections(ctx); err != nil { + log.Printf("xray active connection reset: %v", err) + } + startXrayClientExpiryChecker(store) + } + if err := store.EnsureXrayConfigSchema(ctx); err != nil { + log.Printf("xray config table disabled: %v", err) + } + if err := store.EnsureIfaceUsageTables(ctx); err != nil { + log.Printf("vnstat usage tables disabled: %v", err) + } + if err := store.EnsureIfaceTotalsTable(ctx); err == nil { + rows, err2 := store.LoadIfaceTotals(ctx) + if err2 == nil { + ifaceTotalsMgr = NewIfaceTotalsManager() + ifaceTotalsMgr.Load(rows) + + // Bootstrap with current kernel counters once at startup + if netMap, err3 := readNetDev(); err3 == nil { + for name, ctrs := range netMap { + ifaceTotalsMgr.ApplyKernel(name, ctrs.RxBytes, ctrs.TxBytes) + } + } + } else { + log.Printf("iface totals persistence disabled: %v", err2) + } + } else { + log.Printf("iface totals persistence disabled: %v", err) + } + } + + // start background collector for CPU + interface stats + primeCurrentStats() + startStatsCollector() + + // Turn the per-account byte counters into live up/down speeds for the panel. + startSSHUserRateSampler() + + adminAddr := os.Getenv("ADMIN_HTTP_ADDR") + if adminAddr == "" { + adminAddr = "127.0.0.1:9090" + } + startAdminAPI(store, adminAddr) + + // Start the integrated Xray-core subprocess if configured. + initXrayManager(cfg.Xray) + + // Global banner text (from config or file) — stored in a global so the + // admin API can update it on the fly without a restart. + { + bt := cfg.Banner + if bt == "" && cfg.BannerFile != "" { + if data, err := os.ReadFile(cfg.BannerFile); err == nil { + bt = string(data) + } else { + log.Printf("failed to read banner file %s: %v", cfg.BannerFile, err) + } + } + setBannerText(bt) + } + + sshConfig := &ssh.ServerConfig{ + PasswordCallback: passwordCallback, + PublicKeyCallback: publicKeyCallback, + NoClientAuth: false, + } + + // Optional compatibility mode for legacy SSH clients (weak algorithms). + // Enable only if you must support older embedded/mobile SSH stacks. + // Usage: SSH_LEGACY=1 ./server + if os.Getenv("SSH_LEGACY") == "1" { + sshConfig.Config = ssh.Config{ + Ciphers: []string{ + // Modern first + "chacha20-poly1305@openssh.com", + "aes128-ctr", "aes192-ctr", "aes256-ctr", + // Legacy (weak) + "aes128-cbc", "aes192-cbc", "aes256-cbc", + "3des-cbc", + }, + KeyExchanges: []string{ + // Modern first + "curve25519-sha256", "curve25519-sha256@libssh.org", + "diffie-hellman-group-exchange-sha256", + // Legacy (weak) + "diffie-hellman-group14-sha1", + "diffie-hellman-group1-sha1", + }, + MACs: []string{ + // Modern first + "hmac-sha2-256", "hmac-sha2-512", + // Legacy (weak) + "hmac-sha1", + }, + } + log.Println("[SSH] legacy crypto enabled (weak algorithms allowed)") + } + + // Fancy per-user banner: + // - Optional global banner first + // - Then block: + // Username: user + // ----------------- + // Expiration: 10/12/2025 + // ----------------- + // Max Upload: 10 Mbps + // ----------------- + // Max Download: 10 Mbps + sshConfig.BannerCallback = func(meta ssh.ConnMetadata) string { + var sb strings.Builder + + // Global / custom banner (reads live value so admin-panel edits apply immediately) + if bt := getBannerText(); bt != "" { + sb.WriteString(bt) + if !strings.HasSuffix(bt, "\n") { + sb.WriteString("\n") + } + sb.WriteString("\n") // extra blank line before user block + } + + u, ok := userMgr.Get(meta.User()) + if !ok { + // If user not found (should be rare), just return global banner + return sb.String() + } + + u.mu.Lock() + exp := u.ExpiresAt + up := u.Cfg.LimitMbpsUp + down := u.Cfg.LimitMbpsDown + name := u.Cfg.Username + u.mu.Unlock() + + // BR-style date: dd/MM/yyyy + expStr := "Sem limite" + if exp != nil { + expStr = exp.Local().Format("02/01/2006") + } + sb.WriteString("\n
-----------------
\n") + sb.WriteString("Account Information") + sb.WriteString("\n
-----------------
\n") + sb.WriteString("Username: ") + sb.WriteString(name) + sb.WriteString("\n
-----------------
\n") + + sb.WriteString("Expiration: ") + sb.WriteString(expStr) + sb.WriteString("\n
-----------------
\n") + + sb.WriteString("Max Upload: ") + sb.WriteString(strconv.Itoa(up)) + sb.WriteString(" Mbps") + sb.WriteString("\n
-----------------
\n") + sb.WriteString("Max Download: ") + sb.WriteString(strconv.Itoa(down)) + sb.WriteString(" Mbps") + sb.WriteString("\n
-----------------
\n") + return sb.String() + } + + hostKeyBytes, err := os.ReadFile(cfg.HostKeyFile) + if err != nil { + log.Fatalf("failed to load host key %s: %v", cfg.HostKeyFile, err) + } + hostKey, err := ssh.ParsePrivateKey(hostKeyBytes) + if err != nil { + log.Fatalf("failed to parse host key: %v", err) + } + + // Enforce RSA host key (ssh-rsa) for maximum compatibility with legacy SSH clients. + // If you need ed25519 or other key types, remove this check. + if hostKey.PublicKey().Type() != ssh.KeyAlgoRSA { + log.Fatalf("host key %s is %s; this build requires RSA (ssh-rsa). Generate an RSA key with: ssh-keygen -t rsa -b 2048 -f %s -N \"\"", cfg.HostKeyFile, hostKey.PublicKey().Type(), cfg.HostKeyFile) + } + sshConfig.AddHostKey(hostKey) + + // Store SSH config globally so hot-reloaded serve loops always use the latest. + setSSHConfig(sshConfig) + + // Logging setup. + quietLogs := cfg.Quiet || *quietFlag || userCountEnabled + if quietLogs { + log.SetOutput(io.Discard) + } + startPanelLogLimiter() + + // Initialise default per-connection bandwidth limits and SSH inactivity cleanup. + setDefaultLimits(cfg.DefaultLimitMbpsUp, cfg.DefaultLimitMbpsDown) + setSSHIdleTimeoutFromConfig(cfg.SSHIdleTimeout) + setMaxTotalConnsFromConfig(cfg.MaxTotalConnections) + setPAMAuthEnabled(cfg.PAMAuthEnabled) + + // Initialise listener pools (used for initial startup and hot-reload alike). + publicPool = newListenerPool(serveHTTP80) + localPool = newListenerPool(serveRawSSH) + tlsPool = newTLSListenerPool() + + for _, msg := range normalizeRuntimePorts(cfg) { + log.Printf("startup config fallback: %s", msg) + } + + // Keep a plain, loopback-only SSH endpoint available to local proxy and + // tunnel daemons. It has its own listener pool, so cycling the public proxy + // ports does not close this socket. + for _, e := range localPool.Sync([]string{cfg.LocalSSHListen}) { + log.Printf("failed to start internal SSH listener: %v", e) + } + + // Start the integrated DNSTT and UDPGW if configured. Startup errors are logged + // but do not crash the panel; the admin UI exposes the logs and service status. + if err := startDNSTT(cfg.DNSTT, sshConfig); err != nil { + log.Printf("dnstt auto-start failed: %v", err) + } + if err := startUDPGW(cfg.UDPGW); err != nil { + log.Printf("udpgw auto-start failed: %v", err) + } + + // Start the integrated BHTTP transport and BTUN protocol server. Both relay + // into this process (BHTTP into the built-in SSH server, BTUN into its own + // TUN device with panel-backed authentication), so neither depends on the + // system sshd. Startup errors are logged and surfaced in the admin UI. + if err := startBHTTP(cfg.BHTTP); err != nil { + log.Printf("bhttp auto-start failed: %v", err) + } + if err := startBTUN(cfg.BTUN); err != nil { + log.Printf("btun auto-start failed: %v", err) + } + if err := startHCR(cfg.HCR); err != nil { + log.Printf("hcr auto-start failed: %v", err) + } + + // Start public SSH listeners (listen + extra_listen). + publicAddrs := append([]string{cfg.Listen}, cfg.ExtraListen...) + for _, e := range publicPool.Sync(publicAddrs) { + log.Printf("failed to start listener: %v", e) + } + + // Start TLS forwarder listeners if configured. + for _, e := range tlsPool.Sync(cfg.TLSForwarders) { + log.Printf("failed to start TLS listener: %v", e) + } + + // Start proxy hard auto-restart after the initial listeners are bound. + startProxyAutoRestart(cfg) + + // Print user counts once at startup. + updateUserDisplay() + + // Block forever. Individual accept loops run in goroutines. + select {} +} diff --git a/managed_servers.go b/managed_servers.go new file mode 100644 index 0000000..536065c --- /dev/null +++ b/managed_servers.go @@ -0,0 +1,779 @@ +package main + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "fmt" + "io" + "log" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const managedCredentialPrefix = "enc:v1:" + +func sealManagedCredential(plain string) (string, error) { + return sealCredential(managedCredentialPrefix, plain) +} + +func openManagedCredential(stored string) (string, error) { + return openCredential(managedCredentialPrefix, stored) +} + +func managedServerHTTPClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} + +type ManagedServer struct { + ID int + Name string + BaseURL string + AdminUsername string + AdminKey string + EnableSSH bool + EnableXray bool + IsActive bool + CreatedAt time.Time + UpdatedAt time.Time +} + +type ManagedServerDTO struct { + ID string `json:"id"` + Name string `json:"name"` + BaseURL string `json:"base_url"` + AdminUsername string `json:"admin_username,omitempty"` + EnableSSH bool `json:"enable_ssh"` + EnableXray bool `json:"enable_xray"` + IsActive bool `json:"is_active"` + IsLocal bool `json:"is_local"` + CreatedAt time.Time `json:"created_at,omitempty"` + UpdatedAt time.Time `json:"updated_at,omitempty"` +} + +type ManagedServerPayload struct { + ID string `json:"id"` + Name string `json:"name"` + BaseURL string `json:"base_url"` + AdminUsername string `json:"admin_username"` + AdminKey string `json:"admin_key"` + EnableSSH bool `json:"enable_ssh"` + EnableXray bool `json:"enable_xray"` + IsActive bool `json:"is_active"` +} + +func (s *Store) EnsureManagedServersSchema(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, ` + CREATE TABLE IF NOT EXISTS managed_servers ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + base_url TEXT NOT NULL UNIQUE, + admin_username TEXT NOT NULL DEFAULT 'admin', + admin_key TEXT NOT NULL DEFAULT '', + enable_ssh BOOLEAN NOT NULL DEFAULT TRUE, + enable_xray BOOLEAN NOT NULL DEFAULT TRUE, + is_active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`) + if err != nil { + return err + } + return s.migrateManagedServerCredentials(ctx) +} + +func (s *Store) migrateManagedServerCredentials(ctx context.Context) error { + rows, err := s.db.QueryContext(ctx, `SELECT id, admin_key FROM managed_servers WHERE admin_key <> '' AND admin_key NOT LIKE 'enc:v1:%'`) + if err != nil { + return err + } + type legacyCredential struct { + id int + key string + } + var legacy []legacyCredential + for rows.Next() { + var item legacyCredential + if err := rows.Scan(&item.id, &item.key); err != nil { + rows.Close() + return err + } + legacy = append(legacy, item) + } + if err := rows.Close(); err != nil { + return err + } + for _, item := range legacy { + sealed, err := sealManagedCredential(item.key) + if err != nil { + return fmt.Errorf("encrypt managed server credential %d: %w", item.id, err) + } + if _, err := s.db.ExecContext(ctx, `UPDATE managed_servers SET admin_key=$2 WHERE id=$1`, item.id, sealed); err != nil { + return err + } + } + return nil +} + +func (s *Store) ListManagedServers(ctx context.Context) ([]*ManagedServer, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT id, name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active, created_at, updated_at + FROM managed_servers ORDER BY id ASC`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*ManagedServer + for rows.Next() { + ms := &ManagedServer{} + if err := rows.Scan(&ms.ID, &ms.Name, &ms.BaseURL, &ms.AdminUsername, &ms.AdminKey, &ms.EnableSSH, &ms.EnableXray, &ms.IsActive, &ms.CreatedAt, &ms.UpdatedAt); err != nil { + return nil, err + } + plainKey, err := openManagedCredential(ms.AdminKey) + if err != nil { + return nil, err + } + ms.AdminKey = plainKey + out = append(out, ms) + } + return out, rows.Err() +} + +func (s *Store) GetManagedServer(ctx context.Context, id int) (*ManagedServer, error) { + ms := &ManagedServer{} + err := s.db.QueryRowContext(ctx, ` + SELECT id, name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active, created_at, updated_at + FROM managed_servers WHERE id=$1`, id). + Scan(&ms.ID, &ms.Name, &ms.BaseURL, &ms.AdminUsername, &ms.AdminKey, &ms.EnableSSH, &ms.EnableXray, &ms.IsActive, &ms.CreatedAt, &ms.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + plainKey, err := openManagedCredential(ms.AdminKey) + if err != nil { + return nil, err + } + ms.AdminKey = plainKey + return ms, nil +} + +func (s *Store) UpsertManagedServer(ctx context.Context, p ManagedServerPayload) (*ManagedServer, error) { + name := strings.TrimSpace(p.Name) + baseURL, baseURLErr := validateManagedServerBaseURL(p.BaseURL) + adminUsername := strings.TrimSpace(p.AdminUsername) + if adminUsername == "" { + adminUsername = "admin" + } + if name == "" { + return nil, fmt.Errorf("server name required") + } + if len(name) > 120 || strings.IndexFunc(name, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 { + return nil, fmt.Errorf("invalid server name") + } + if len(adminUsername) > 128 || strings.IndexFunc(adminUsername, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 { + return nil, fmt.Errorf("invalid admin username") + } + if len(p.AdminKey) > 4096 || strings.IndexFunc(p.AdminKey, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 { + return nil, fmt.Errorf("invalid admin credential") + } + if baseURLErr != nil { + return nil, baseURLErr + } + if p.ID != "" && p.ID != "local" { + id, err := strconv.Atoi(p.ID) + if err != nil || id <= 0 { + return nil, fmt.Errorf("invalid server id") + } + if strings.TrimSpace(p.AdminKey) == "" { + _, err = s.db.ExecContext(ctx, ` + UPDATE managed_servers + SET name=$2, base_url=$3, admin_username=$4, enable_ssh=$5, enable_xray=$6, is_active=$7, updated_at=NOW() + WHERE id=$1`, id, name, baseURL, adminUsername, p.EnableSSH, p.EnableXray, p.IsActive) + } else { + sealedKey, sealErr := sealManagedCredential(p.AdminKey) + if sealErr != nil { + return nil, fmt.Errorf("encrypt admin credential: %w", sealErr) + } + _, err = s.db.ExecContext(ctx, ` + UPDATE managed_servers + SET name=$2, base_url=$3, admin_username=$4, admin_key=$5, enable_ssh=$6, enable_xray=$7, is_active=$8, updated_at=NOW() + WHERE id=$1`, id, name, baseURL, adminUsername, sealedKey, p.EnableSSH, p.EnableXray, p.IsActive) + } + if err != nil { + return nil, err + } + return s.GetManagedServer(ctx, id) + } + if strings.TrimSpace(p.AdminKey) == "" { + return nil, fmt.Errorf("admin key/password required") + } + sealedKey, err := sealManagedCredential(p.AdminKey) + if err != nil { + return nil, fmt.Errorf("encrypt admin credential: %w", err) + } + var id int + err = s.db.QueryRowContext(ctx, ` + INSERT INTO managed_servers (name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active) + VALUES ($1,$2,$3,$4,$5,$6,$7) + ON CONFLICT (base_url) DO UPDATE SET + name=EXCLUDED.name, + admin_username=EXCLUDED.admin_username, + admin_key=EXCLUDED.admin_key, + enable_ssh=EXCLUDED.enable_ssh, + enable_xray=EXCLUDED.enable_xray, + is_active=EXCLUDED.is_active, + updated_at=NOW() + RETURNING id`, name, baseURL, adminUsername, sealedKey, p.EnableSSH, p.EnableXray, p.IsActive).Scan(&id) + if err != nil { + return nil, err + } + return s.GetManagedServer(ctx, id) +} + +func (s *Store) DeleteManagedServer(ctx context.Context, id int) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM managed_servers WHERE id=$1`, id) + return err +} + +func managedServerToDTO(ms *ManagedServer) ManagedServerDTO { + return ManagedServerDTO{ + ID: strconv.Itoa(ms.ID), + Name: ms.Name, + BaseURL: ms.BaseURL, + AdminUsername: ms.AdminUsername, + EnableSSH: ms.EnableSSH, + EnableXray: ms.EnableXray, + IsActive: ms.IsActive, + CreatedAt: ms.CreatedAt, + UpdatedAt: ms.UpdatedAt, + } +} + +func localManagedServerDTO() ManagedServerDTO { + cfg := getGlobalCfg() + xrayEnabled := cfg != nil && cfg.Xray != nil && cfg.Xray.Enabled + return ManagedServerDTO{ + ID: "local", + Name: "Master node", + BaseURL: "local", + EnableSSH: true, + EnableXray: xrayEnabled, + IsActive: true, + IsLocal: true, + } +} + +func normalizeManagedServerBaseURL(raw string) string { + normalized, _ := validateManagedServerBaseURL(raw) + return normalized +} + +func validateManagedServerBaseURL(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", fmt.Errorf("base url required") + } + lowerRaw := strings.ToLower(raw) + if !strings.HasPrefix(lowerRaw, "http://") && !strings.HasPrefix(lowerRaw, "https://") { + raw = "http://" + raw + } + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Host == "" { + return "", fmt.Errorf("invalid base url") + } + if u.Scheme != "http" && u.Scheme != "https" { + return "", fmt.Errorf("base url must use http or https") + } + if u.User != nil { + return "", fmt.Errorf("base url must not contain credentials") + } + if u.Path != "" && u.Path != "/" { + return "", fmt.Errorf("base url must not contain a path") + } + if ip := net.ParseIP(u.Hostname()); ip != nil && (ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) { + return "", fmt.Errorf("base url uses a forbidden address") + } + u.Path = "" + u.RawQuery = "" + u.Fragment = "" + return strings.TrimRight(u.String(), "/"), nil +} + +func requestedServerID(r *http.Request) string { + id := strings.TrimSpace(r.URL.Query().Get("server_id")) + if id == "" { + id = strings.TrimSpace(r.URL.Query().Get("server")) + } + return id +} + +func managedServerFromID(ctx context.Context, store *Store, id string) (*ManagedServer, bool, error) { + id = strings.TrimSpace(id) + if id == "" || id == "local" || id == "0" { + return nil, false, nil + } + if store == nil { + return nil, false, fmt.Errorf("database not configured") + } + n, err := strconv.Atoi(id) + if err != nil || n <= 0 { + return nil, false, fmt.Errorf("invalid server id") + } + ms, err := store.GetManagedServer(ctx, n) + if err != nil { + return nil, false, err + } + if ms == nil { + return nil, false, fmt.Errorf("server not found") + } + if !ms.IsActive { + return nil, false, fmt.Errorf("server is disabled") + } + return ms, true, nil +} + +func remoteLoginToken(ctx context.Context, ms *ManagedServer) (string, error) { + body, _ := json.Marshal(map[string]string{"username": ms.AdminUsername, "password": ms.AdminKey}) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, ms.BaseURL+"/api/auth/login", bytes.NewReader(body)) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/json") + client := managedServerHTTPClient(15 * time.Second) + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 128*1024)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("remote login failed: %s", strings.TrimSpace(string(data))) + } + var out struct { + Token string `json:"token"` + } + if err := json.Unmarshal(data, &out); err != nil || out.Token == "" { + return "", fmt.Errorf("remote login returned no token") + } + return out.Token, nil +} + +func proxyManagedServer(ctx context.Context, ms *ManagedServer, method, path string, body []byte, contentType string) (int, []byte, string, error) { + token, err := remoteLoginToken(ctx, ms) + if err != nil { + return 0, nil, "", err + } + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + req, err := http.NewRequestWithContext(ctx, method, ms.BaseURL+path, bytes.NewReader(body)) + if err != nil { + return 0, nil, "", err + } + if contentType == "" { + contentType = "application/json" + } + req.Header.Set("Content-Type", contentType) + req.Header.Set("X-Session-Token", token) + client := managedServerHTTPClient(30 * time.Second) + resp, err := client.Do(req) + if err != nil { + return 0, nil, "", err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024)) + return resp.StatusCode, data, resp.Header.Get("Content-Type"), nil +} + +func handleManagedProxyOrLocal(store *Store, local http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if proxyManagedServerFromRequest(w, r, store, "", nil, "") { + return + } + local(w, r) + } +} + +func writeProxyResponse(w http.ResponseWriter, status int, body []byte, contentType string) { + if contentType != "" { + w.Header().Set("Content-Type", contentType) + } + if status == 0 { + status = http.StatusBadGateway + } + w.WriteHeader(status) + if len(body) > 0 { + _, _ = w.Write(body) + } +} + +func proxyManagedServerFromRequest(w http.ResponseWriter, r *http.Request, store *Store, remotePath string, body []byte, filterOwner string) bool { + ms, remote, err := managedServerFromID(r.Context(), store, requestedServerID(r)) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return true + } + if !remote { + return false + } + if remotePath == "" { + remotePath = r.URL.Path + if r.URL.RawQuery != "" { + q := r.URL.Query() + q.Del("server_id") + q.Del("server") + if enc := q.Encode(); enc != "" { + remotePath += "?" + enc + } + } + } + if body == nil && r.Body != nil && r.Method != http.MethodGet { + body, _ = io.ReadAll(io.LimitReader(r.Body, 2*1024*1024)) + } + status, data, ct, err := proxyManagedServer(r.Context(), ms, r.Method, remotePath, body, r.Header.Get("Content-Type")) + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return true + } + if status >= 200 && status < 300 && filterOwner != "" && strings.Contains(ct, "json") { + if filtered, ok := filterRemoteOwnerJSON(remotePath, data, filterOwner); ok { + data = filtered + } + } + writeProxyResponse(w, status, data, ct) + return true +} + +func filterRemoteOwnerJSON(path string, data []byte, owner string) ([]byte, bool) { + if owner == "" || len(data) == 0 { + return data, false + } + if strings.HasPrefix(path, "/api/users") { + var rows []map[string]interface{} + if err := json.Unmarshal(data, &rows); err != nil { + return data, false + } + out := rows[:0] + for _, row := range rows { + if strings.TrimSpace(fmt.Sprint(row["owner_username"])) == owner { + out = append(out, row) + } + } + filtered, _ := json.Marshal(out) + return filtered, true + } + if strings.HasPrefix(path, "/api/xray/inbounds") { + var inbounds []map[string]interface{} + if err := json.Unmarshal(data, &inbounds); err != nil { + return data, false + } + for _, ib := range inbounds { + clients, _ := ib["clients"].([]interface{}) + filtered := make([]interface{}, 0, len(clients)) + for _, c := range clients { + m, _ := c.(map[string]interface{}) + if strings.TrimSpace(fmt.Sprint(m["owner_username"])) == owner { + filtered = append(filtered, c) + } + } + ib["clients"] = filtered + } + filtered, _ := json.Marshal(inbounds) + return filtered, true + } + return data, false +} + +func handleServers(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + sess := sessionFromCtx(r.Context()) + switch r.Method { + case http.MethodGet: + rows, err := store.ListManagedServers(r.Context()) + if err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + out := []ManagedServerDTO{localManagedServerDTO()} + for _, ms := range rows { + if sess != nil && sess.Role == RoleReseller && !ms.IsActive { + continue + } + dto := managedServerToDTO(ms) + if sess != nil && sess.Role == RoleReseller { + dto.AdminUsername = "" + } + out = append(out, dto) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(out) + case http.MethodPost: + if sess == nil || sess.Role != RoleSuperAdmin { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + var p ManagedServerPayload + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + ms, err := store.UpsertManagedServer(r.Context(), p) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(managedServerToDTO(ms)) + case http.MethodDelete: + if sess == nil || sess.Role != RoleSuperAdmin { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + idStr := strings.TrimSpace(r.URL.Query().Get("id")) + id, err := strconv.Atoi(idStr) + if err != nil || id <= 0 { + http.Error(w, "invalid server id", http.StatusBadRequest) + return + } + if err := store.DeleteManagedServer(r.Context(), id); err != nil { + http.Error(w, "db error", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + } +} + +func handleServerTest(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + var p ManagedServerPayload + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + ms := &ManagedServer{Name: p.Name, BaseURL: normalizeManagedServerBaseURL(p.BaseURL), AdminUsername: strings.TrimSpace(p.AdminUsername), AdminKey: p.AdminKey, EnableSSH: p.EnableSSH, EnableXray: p.EnableXray, IsActive: true} + if p.ID != "" && p.ID != "local" && (ms.BaseURL == "" || ms.AdminKey == "") { + id, _ := strconv.Atoi(p.ID) + if id > 0 { + stored, err := store.GetManagedServer(r.Context(), id) + if err == nil && stored != nil { + if ms.BaseURL == "" { + ms.BaseURL = stored.BaseURL + } + if ms.AdminUsername == "" { + ms.AdminUsername = stored.AdminUsername + } + if ms.AdminKey == "" { + ms.AdminKey = stored.AdminKey + } + } + } + } + if ms.AdminUsername == "" { + ms.AdminUsername = "admin" + } + if ms.BaseURL == "" || ms.AdminKey == "" { + http.Error(w, "base url and admin key/password required", http.StatusBadRequest) + return + } + token, err := remoteLoginToken(r.Context(), ms) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + _ = token + status, data, _, err := proxyManagedServer(r.Context(), ms, http.MethodGet, "/api/auth/me", nil, "application/json") + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + if status < 200 || status >= 300 { + http.Error(w, strings.TrimSpace(string(data)), http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "message": "remote login ok"}) + } +} + +func handleManagedServerConfig(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + id := requestedServerID(r) + if id == "" || id == "local" || id == "0" { + handleServerConfig(w, r) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + body := []byte(nil) + if r.Method == http.MethodPost { + var err error + body, err = io.ReadAll(io.LimitReader(r.Body, 512*1024)) + if err != nil { + http.Error(w, "failed to read body", http.StatusBadRequest) + return + } + } + ms, remote, err := managedServerFromID(r.Context(), store, id) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if !remote { + handleServerConfig(w, r) + return + } + status, data, ct, err := proxyManagedServer(r.Context(), ms, r.Method, "/api/server/config", body, "application/json") + if err != nil { + log.Printf("managed server config proxy %s: %v", ms.BaseURL, err) + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + } +} + +func remoteSSHUserOwner(ctx context.Context, ms *ManagedServer, username string) (owner string, exists bool, err error) { + if username == "" { + return "", false, nil + } + status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/users", nil, "application/json") + if err != nil || status < 200 || status >= 300 { + if err == nil { + err = fmt.Errorf("remote users returned HTTP %d", status) + } + return "", false, err + } + var rows []map[string]interface{} + if err := json.Unmarshal(data, &rows); err != nil { + return "", false, err + } + for _, row := range rows { + if fmt.Sprint(row["username"]) == username { + return strings.TrimSpace(fmt.Sprint(row["owner_username"])), true, nil + } + } + return "", false, nil +} + +func remoteSSHUserOwned(ctx context.Context, ms *ManagedServer, username, owner string) bool { + actualOwner, exists, err := remoteSSHUserOwner(ctx, ms, username) + return err == nil && exists && actualOwner == owner +} + +func remoteXrayClientOwner(ctx context.Context, ms *ManagedServer, uuid string) (owner string, exists bool, err error) { + if uuid == "" { + return "", false, nil + } + status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/xray/inbounds", nil, "application/json") + if err != nil || status < 200 || status >= 300 { + if err == nil { + err = fmt.Errorf("remote Xray inbounds returned HTTP %d", status) + } + return "", false, err + } + var inbounds []map[string]interface{} + if err := json.Unmarshal(data, &inbounds); err != nil { + return "", false, err + } + for _, ib := range inbounds { + clients, _ := ib["clients"].([]interface{}) + for _, c := range clients { + m, _ := c.(map[string]interface{}) + if fmt.Sprint(m["id"]) == uuid { + return strings.TrimSpace(fmt.Sprint(m["owner_username"])), true, nil + } + } + } + return "", false, nil +} + +func remoteXrayClientOwned(ctx context.Context, ms *ManagedServer, uuid, owner string) bool { + actualOwner, exists, err := remoteXrayClientOwner(ctx, ms, uuid) + return err == nil && exists && actualOwner == owner +} + +func countOwnedQuotaAcrossManagedServers(ctx context.Context, store *Store, owner string) (int, error) { + if store == nil || owner == "" { + return 0, nil + } + total := countOwnedQuota(ctx, store, owner) + servers, err := store.ListManagedServers(ctx) + if err != nil { + return 0, err + } + for _, ms := range servers { + if !ms.IsActive { + continue + } + if ms.EnableSSH { + status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/users", nil, "application/json") + if err != nil || status < 200 || status >= 300 { + if err == nil { + err = fmt.Errorf("remote users returned HTTP %d", status) + } + return 0, err + } + var users []map[string]interface{} + if err := json.Unmarshal(data, &users); err != nil { + return 0, err + } + for _, user := range users { + if strings.TrimSpace(fmt.Sprint(user["owner_username"])) == owner { + total++ + } + } + } + if ms.EnableXray { + status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/xray/inbounds", nil, "application/json") + if err != nil || status < 200 || status >= 300 { + if err == nil { + err = fmt.Errorf("remote Xray inbounds returned HTTP %d", status) + } + return 0, err + } + var inbounds []map[string]interface{} + if err := json.Unmarshal(data, &inbounds); err != nil { + return 0, err + } + for _, inbound := range inbounds { + clients, _ := inbound["clients"].([]interface{}) + for _, client := range clients { + item, _ := client.(map[string]interface{}) + if strings.TrimSpace(fmt.Sprint(item["owner_username"])) == owner { + total++ + } + } + } + } + } + return total, nil +} diff --git a/pam_auth.go b/pam_auth.go new file mode 100644 index 0000000..ec2a95a --- /dev/null +++ b/pam_auth.go @@ -0,0 +1,227 @@ +package main + +import ( + "context" + "crypto/subtle" + "errors" + "fmt" + "log" + "os" + "strconv" + "strings" + "sync/atomic" + "time" + + "github.com/GehirnInc/crypt" + _ "github.com/GehirnInc/crypt/apr1_crypt" + _ "github.com/GehirnInc/crypt/md5_crypt" + _ "github.com/GehirnInc/crypt/sha256_crypt" + _ "github.com/GehirnInc/crypt/sha512_crypt" + "github.com/openwall/yescrypt-go" + "golang.org/x/crypto/bcrypt" +) + +const ( + shadowFile = "/etc/shadow" + passwdFile = "/etc/passwd" + + // minLoginUID / nobodyUID bound the accounts eligible for auto-import. + // Regular human login accounts start at UID 1000 on Debian/Ubuntu; system + // and service accounts (and "nobody") are excluded. + minLoginUID = 1000 + nobodyUID = 65534 +) + +var errNoSystemPassword = errors.New("account has no usable password") + +// pamLogger writes PAM auth diagnostics straight to stderr (captured by +// journald) so they remain visible even when "Quiet Logs" redirects the default +// logger to io.Discard. Use pamLogf for anything an operator needs to see when +// debugging why a system login was accepted or refused. +var pamLogger = log.New(os.Stderr, "", log.LstdFlags) + +func pamLogf(format string, args ...interface{}) { pamLogger.Printf(format, args...) } + +// pamAuthEnabled mirrors Config.PAMAuthEnabled and is toggled live on config +// reload. Guarded atomically so passwordCallback can read it lock-free. +var pamAuthEnabled atomic.Bool + +func setPAMAuthEnabled(v bool) { + pamAuthEnabled.Store(v) + state := "disabled" + if v { + state = "ENABLED" + } + pamLogf("PAM: system (Linux /etc/shadow) login is now %s", state) +} +func isPAMAuthEnabled() bool { return pamAuthEnabled.Load() } + +// importPAMUser registers a freshly PAM-authenticated account in the running +// user manager and persists it (marked use_pam) so it shows up in the panel and +// later logins are re-verified against the system password. Idempotent: a +// second concurrent/subsequent login for the same user is a no-op. +func importPAMUser(username string) { + cfg := UserConfig{Username: username, UsePAM: true} + // Carry over the Linux account expiry (/etc/shadow field 8) so the panel's + // "Vence em" shows the real expiration instead of "—". + var expPtr *time.Time + if exp := shadowAccountExpiry(username); exp != nil { + cfg.ExpiresAt = exp.Format(time.RFC3339) + expPtr = exp + } + st := &UserState{Cfg: cfg, ExpiresAt: expPtr} + if !userMgr.AddIfAbsent(st) { + return // already present in memory + } + pamLogf("PAM: auto-imported system user %s into the panel", username) + if statsStore != nil { + if err := statsStore.UpsertUser(context.Background(), cfg); err != nil { + pamLogf("PAM: failed to persist auto-imported user %s: %v", username, err) + } + } +} + +// isRegularLoginUser reports whether username is a regular human login account +// (UID >= 1000 and not "nobody"), by parsing /etc/passwd. System/service +// accounts and root are excluded from auto-import. +func isRegularLoginUser(username string) bool { + data, err := os.ReadFile(passwdFile) + if err != nil { + pamLogf("PAM: cannot read %s: %v", passwdFile, err) + return false + } + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimRight(line, "\r") + fields := strings.Split(line, ":") + if len(fields) < 3 || fields[0] != username { + continue + } + uid, err := strconv.Atoi(fields[2]) + if err != nil { + return false + } + return uid >= minLoginUID && uid != nobodyUID + } + return false +} + +// shadowAccountExpiry returns the account expiration date from /etc/shadow +// field 8 (days since 1970-01-01), or nil if the account never expires (empty +// field) or the value is unusable. This is the `chage -E` / `useradd -e` date, +// which maps to the panel's per-user expiry. +func shadowAccountExpiry(username string) *time.Time { + data, err := os.ReadFile(shadowFile) + if err != nil { + return nil + } + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Split(strings.TrimRight(line, "\r"), ":") + if len(fields) < 8 || fields[0] != username { + continue + } + expStr := strings.TrimSpace(fields[7]) + if expStr == "" { + return nil // no account expiry set + } + days, err := strconv.Atoi(expStr) + if err != nil || days <= 0 { + return nil + } + t := time.Unix(int64(days)*86400, 0).UTC() + return &t + } + return nil +} + +// authenticatePAM verifies password against the Linux system account matching +// username. It reads the account's hash from /etc/shadow (the panel runs as +// root) and recomputes it with the same algorithm — this is the "just the auth" +// behaviour: the supplied password is checked exactly as the system would, +// with no account/session management and nothing to do with the SSH daemon. +// +// It is called "PAM" for continuity with the user-facing flag, but it does not +// link libpam; it verifies the crypt(3) hash directly. Supported hash formats: +// yescrypt ($y$), sha512-crypt ($6$), sha256-crypt ($5$), md5-crypt ($1$), +// apr1 ($apr1$) and bcrypt ($2a$/$2b$/$2y$). Returns nil on success. +func authenticatePAM(username, password string) error { + if username == "" { + return errors.New("shadow: empty username") + } + hash, err := lookupShadowHash(username) + if err != nil { + return err + } + return verifyCryptHash(hash, password) +} + +// lookupShadowHash returns the password hash field for username from /etc/shadow. +func lookupShadowHash(username string) (string, error) { + data, err := os.ReadFile(shadowFile) + if err != nil { + return "", fmt.Errorf("read %s: %w", shadowFile, err) + } + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimRight(line, "\r") + if line == "" { + continue + } + fields := strings.Split(line, ":") + if len(fields) < 2 || fields[0] != username { + continue + } + hash := fields[1] + // Empty, or locked/disabled accounts (! or * in the hash field) have no + // password that any input can match — reject rather than risk a match. + if hash == "" || strings.HasPrefix(hash, "!") || strings.HasPrefix(hash, "*") { + return "", errNoSystemPassword + } + return hash, nil + } + return "", fmt.Errorf("shadow: user %q not found", username) +} + +// verifyCryptHash checks password against a crypt(3)-style hash string, +// dispatching on the hash prefix. Returns nil only on an exact match. +func verifyCryptHash(hash, password string) error { + switch { + case strings.HasPrefix(hash, "$y$"): + computed, err := yescrypt.Hash([]byte(password), []byte(hash)) + if err != nil { + return fmt.Errorf("yescrypt: %w", err) + } + if subtle.ConstantTimeCompare(computed, []byte(hash)) == 1 { + return nil + } + return errors.New("password mismatch") + case strings.HasPrefix(hash, "$2a$"), strings.HasPrefix(hash, "$2b$"), strings.HasPrefix(hash, "$2y$"): + return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + case crypt.IsHashSupported(hash): + return crypt.NewFromHash(hash).Verify(hash, []byte(password)) + case isTraditionalDES(hash): + computed, err := desCrypt(password, hash) + if err != nil { + return fmt.Errorf("descrypt: %w", err) + } + if subtle.ConstantTimeCompare([]byte(computed), []byte(hash)) == 1 { + return nil + } + return errors.New("password mismatch") + default: + return fmt.Errorf("shadow: unsupported hash format") + } +} + +// isTraditionalDES reports whether hash looks like a classic 13-character +// DES crypt(3) hash (2 salt chars + 11 hash chars, all from the crypt alphabet, +// no "$" scheme prefix). Used by old Linux/UNIX accounts. +func isTraditionalDES(hash string) bool { + if len(hash) != 13 { + return false + } + for i := 0; i < len(hash); i++ { + if crypt64Decode(hash[i]) < 0 { + return false + } + } + return true +} diff --git a/pam_auth_vectors_test.go b/pam_auth_vectors_test.go new file mode 100644 index 0000000..99364bc --- /dev/null +++ b/pam_auth_vectors_test.go @@ -0,0 +1,51 @@ +package main + +import "testing" + +// Known crypt(3) test vectors covering the formats found in /etc/shadow across +// old and new Linux. verifyCryptHash must accept the right password and reject +// the wrong one for each. +func TestVerifyCryptHashVectors(t *testing.T) { + cases := []struct { + name string + hash string + pw string + }{ + { + name: "sha512crypt $6$ (glibc, older Linux)", + // openssl passwd -6 -salt saltstring "Hello world!" + hash: "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1", + pw: "Hello world!", + }, + { + name: "yescrypt $y$ (Debian 11+/Ubuntu 22.04+)", + hash: "$y$j9T$e8R9q85ZuzUkArEUurdtS.$esON.7y6H.u3UCPVCpbRFueRpAut2n2cMf1EhpjbuiC", + pw: "pleaseletmein", + }, + { + // Real DES-crypt account from the production server's /etc/shadow. + name: "traditional DES (old Linux) — testedragon", + hash: "pae9A3UKpfaU6", + pw: "testedragon", + }, + { + name: "traditional DES (old Linux) — ipv6dragon", + hash: "pa9eao3LI6u.6", + pw: "0tMGUL9chq8D", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if err := verifyCryptHash(c.hash, c.pw); err != nil { + t.Errorf("correct password REJECTED: %v", err) + } + // Build a wrong password that differs in the FIRST character, so the + // check is meaningful even for traditional DES (which only considers + // the first 8 bytes of the password). + wrong := "Z" + c.pw + if err := verifyCryptHash(c.hash, wrong); err == nil { + t.Errorf("wrong password ACCEPTED") + } + }) + } +} diff --git a/panel_log_limiter.go b/panel_log_limiter.go new file mode 100644 index 0000000..b52ef7d --- /dev/null +++ b/panel_log_limiter.go @@ -0,0 +1,105 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +const ( + defaultPanelLogMaxBytes int64 = 1 * 1024 * 1024 + defaultPanelLogCheckEvery = 10 * time.Second +) + +type panelLogResetResponse struct { + OK bool `json:"ok"` + Path string `json:"path"` + MaxBytes int64 `json:"max_bytes"` +} + +func panelLogFilePath() string { + path := strings.TrimSpace(os.Getenv("PANEL_LOG_FILE")) + if path == "" { + path = defaultPanelLogFile + } + return path +} + +func panelLogMaxBytes() int64 { + raw := strings.TrimSpace(os.Getenv("PANEL_LOG_MAX_BYTES")) + if raw == "" { + return defaultPanelLogMaxBytes + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil || n <= 0 { + return defaultPanelLogMaxBytes + } + // Do not allow a tiny limit that would cause continuous truncation. + if n < 64*1024 { + return 64 * 1024 + } + return n +} + +func startPanelLogLimiter() { + path := panelLogFilePath() + maxBytes := panelLogMaxBytes() + if path == "" || maxBytes <= 0 { + return + } + go func() { + _ = enforcePanelLogLimit(path, maxBytes) + ticker := time.NewTicker(defaultPanelLogCheckEvery) + defer ticker.Stop() + for range ticker.C { + _ = enforcePanelLogLimit(path, maxBytes) + } + }() +} + +func enforcePanelLogLimit(path string, maxBytes int64) error { + st, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if st.Size() <= maxBytes { + return nil + } + return truncatePanelLog(path, maxBytes, "automatic 1 MiB log limit") +} + +func truncatePanelLog(path string, maxBytes int64, reason string) error { + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return err + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + return err + } + defer f.Close() + _, err = fmt.Fprintf(f, "%s sshpanel: panel log cleaned (%s, max=%d bytes)\n", time.Now().Format(time.RFC3339), reason, maxBytes) + return err +} + +func handleSystemLogsReset(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + path := panelLogFilePath() + maxBytes := panelLogMaxBytes() + if err := truncatePanelLog(path, maxBytes, "manual clean from admin panel"); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(panelLogResetResponse{OK: true, Path: path, MaxBytes: maxBytes}) +} diff --git a/proxy_autorestart.go b/proxy_autorestart.go new file mode 100644 index 0000000..91d53d0 --- /dev/null +++ b/proxy_autorestart.go @@ -0,0 +1,176 @@ +package main + +import ( + "context" + "log" + "strings" + "sync" + "time" +) + +var ( + proxyAutoMu sync.Mutex + proxyAutoCancel context.CancelFunc +) + +// startProxyAutoRestart starts a watchdog that periodically hard-restarts the +// public SSH/HTTP proxy layer. Unlike a normal hot reload, this intentionally +// closes active SSH sessions so the behavior is close to a service reboot. +func startProxyAutoRestart(cfg *Config) { + interval := proxyAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := proxyAutoRestartGrace(cfg) + cfgCopy := cloneProxyRestartConfig(cfg) + ctx, cancel := context.WithCancel(context.Background()) + + proxyAutoMu.Lock() + if proxyAutoCancel != nil { + proxyAutoCancel() + } + proxyAutoCancel = cancel + proxyAutoMu.Unlock() + + go func() { + t := time.NewTicker(interval) + defer t.Stop() + log.Printf("proxy auto restart enabled: interval=%s grace=%s mode=hard", interval, grace) + for { + select { + case <-ctx.Done(): + return + case <-t.C: + restartProxyHard(ctx, cfgCopy, grace) + } + } + }() +} + +func stopProxyAutoRestart() { + proxyAutoMu.Lock() + defer proxyAutoMu.Unlock() + if proxyAutoCancel != nil { + proxyAutoCancel() + proxyAutoCancel = nil + } +} + +func cloneProxyRestartConfig(cfg *Config) *Config { + if cfg == nil { + return nil + } + out := &Config{ + Listen: cfg.Listen, + ProxyAutoRestartInterval: cfg.ProxyAutoRestartInterval, + ProxyAutoRestartGrace: cfg.ProxyAutoRestartGrace, + } + out.ExtraListen = append([]string(nil), cfg.ExtraListen...) + out.TLSForwarders = append([]TLSForwarderConfig(nil), cfg.TLSForwarders...) + return out +} + +func restartProxyHard(ctx context.Context, cfg *Config, grace time.Duration) { + if cfg == nil { + return + } + log.Printf("proxy auto restart: stopping public proxy listeners and active SSH sessions") + if publicPool != nil { + publicPool.StopAll("proxy auto restart") + } + if tlsPool != nil { + tlsPool.StopAll("proxy auto restart") + } + closed := userMgr.DisconnectAll() + if closed > 0 { + log.Printf("proxy auto restart: closed %d active SSH session(s)", closed) + } + if !sleepOrContextDone(ctx, grace) { + return + } + + publicAddrs := append([]string{cfg.Listen}, cfg.ExtraListen...) + for attempt := 1; ; attempt++ { + errs := []error{} + if publicPool != nil { + errs = append(errs, publicPool.Sync(publicAddrs)...) + } + if tlsPool != nil { + errs = append(errs, tlsPool.Sync(cfg.TLSForwarders)...) + } + + ok := len(errs) == 0 + if publicPool != nil && !publicPool.HasAll(publicAddrs) { + ok = false + } + if tlsPool != nil && !tlsPool.HasAll(cfg.TLSForwarders) { + ok = false + } + if ok { + log.Printf("proxy auto restart: public proxy restarted") + return + } + + for _, err := range errs { + log.Printf("proxy auto restart: start attempt %d failed: %v", attempt, err) + } + if len(errs) == 0 { + log.Printf("proxy auto restart: start attempt %d incomplete; one or more listeners are still down", attempt) + } + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + } +} + +func proxyAutoRestartInterval(cfg *Config) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.ProxyAutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + log.Printf("proxy auto restart disabled: invalid interval %q: %v", raw, err) + return 0 + } + if d < time.Minute { + log.Printf("proxy auto restart disabled: interval %q is below minimum 1m", raw) + return 0 + } + return d +} + +func proxyAutoRestartGrace(cfg *Config) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.ProxyAutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.ProxyAutoRestartGrace)) + if err != nil || d < 0 { + log.Printf("proxy auto restart: invalid grace %q, using 2s", cfg.ProxyAutoRestartGrace) + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +func sleepOrContextDone(ctx context.Context, d time.Duration) bool { + if d <= 0 { + select { + case <-ctx.Done(): + return false + default: + return true + } + } + select { + case <-ctx.Done(): + return false + case <-time.After(d): + return true + } +} diff --git a/quota.go b/quota.go new file mode 100644 index 0000000..7210a1f --- /dev/null +++ b/quota.go @@ -0,0 +1,367 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/time/rate" +) + +const ( + quotaActionBlock = "block" + quotaActionThrottle = "throttle" +) + +var errDataQuotaExceeded = errors.New("data quota exceeded") + +func normalizeQuotaAction(v string) string { + if strings.EqualFold(strings.TrimSpace(v), quotaActionThrottle) { + return quotaActionThrottle + } + return quotaActionBlock +} + +func quotaThrottleMbpsOrDefault(v int) int { + if v <= 0 { + return 1 + } + return v +} + +type sshTrafficDelta struct { + Uplink int64 + Downlink int64 +} + +var ( + sshTrafficPersistenceMu sync.Mutex + sshTrafficDirtyMu sync.Mutex + sshTrafficDirty = make(map[string]*UserState) +) + +func markSSHUserTrafficDirty(u *UserState) { + if u == nil || strings.TrimSpace(u.Cfg.Username) == "" { + return + } + sshTrafficDirtyMu.Lock() + sshTrafficDirty[u.Cfg.Username] = u + sshTrafficDirtyMu.Unlock() +} + +func takeSSHUserTrafficDirty() map[string]*UserState { + sshTrafficDirtyMu.Lock() + dirty := sshTrafficDirty + sshTrafficDirty = make(map[string]*UserState) + sshTrafficDirtyMu.Unlock() + return dirty +} + +func clearSSHUserTrafficDirty(username string, u *UserState) { + sshTrafficDirtyMu.Lock() + if current := sshTrafficDirty[username]; u == nil || current == u { + delete(sshTrafficDirty, username) + } + sshTrafficDirtyMu.Unlock() +} + +func (s *Store) AddSSHUserTrafficBatch(ctx context.Context, deltas map[string]sshTrafficDelta) error { + if s == nil || len(deltas) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + stmt, err := tx.PrepareContext(ctx, ` + UPDATE ssh_users SET + total_uplink_bytes = GREATEST(total_uplink_bytes + GREATEST($2::BIGINT, 0), 0), + total_downlink_bytes = GREATEST(total_downlink_bytes + GREATEST($3::BIGINT, 0), 0) + WHERE username = $1`) + if err != nil { + _ = tx.Rollback() + return err + } + defer stmt.Close() + for username, d := range deltas { + if strings.TrimSpace(username) == "" || (d.Uplink == 0 && d.Downlink == 0) { + continue + } + if _, err := stmt.ExecContext(ctx, username, d.Uplink, d.Downlink); err != nil { + _ = tx.Rollback() + return err + } + } + return tx.Commit() +} + +func (s *Store) ResetSSHUserTraffic(ctx context.Context, username string) error { + if s == nil || strings.TrimSpace(username) == "" { + return nil + } + _, err := s.db.ExecContext(ctx, ` + UPDATE ssh_users + SET total_uplink_bytes = 0, total_downlink_bytes = 0 + WHERE username = $1`, username) + return err +} + +func initSSHRuntimeUsage(u *UserState, uplink, downlink int64) { + if u == nil { + return + } + if uplink < 0 { + uplink = 0 + } + if downlink < 0 { + downlink = 0 + } + atomic.StoreInt64(&u.TotalUplinkBytes, uplink) + atomic.StoreInt64(&u.TotalDownlinkBytes, downlink) + atomic.StoreInt64(&u.totalBytes, uplink+downlink) + atomic.StoreInt64(&u.pendingUplinkBytes, 0) + atomic.StoreInt64(&u.pendingDownlinkBytes, 0) +} + +func resetSSHRuntimeUsageLocked(u *UserState) { + if u == nil { + return + } + initSSHRuntimeUsage(u, 0, 0) + u.mu.Lock() + u.quotaLimiter = nil + u.quotaLimiterMbps = 0 + u.mu.Unlock() +} + +func resetSSHRuntimeUsage(username string) { + u, ok := userMgr.Get(username) + if !ok || u == nil { + return + } + u.trafficMu.Lock() + resetSSHRuntimeUsageLocked(u) + clearSSHUserTrafficDirty(username, u) + u.trafficMu.Unlock() +} + +func resetSSHUserTrafficAccounting(ctx context.Context, store *Store, username string) error { + u, _ := userMgr.Get(username) + if u != nil { + u.trafficMu.Lock() + defer u.trafficMu.Unlock() + } + sshTrafficPersistenceMu.Lock() + defer sshTrafficPersistenceMu.Unlock() + if err := store.ResetSSHUserTraffic(ctx, username); err != nil { + return err + } + if u != nil { + resetSSHRuntimeUsageLocked(u) + clearSSHUserTrafficDirty(username, u) + } + return nil +} + +func sshUserQuotaBlocked(u *UserState) bool { + if u == nil { + return false + } + u.mu.Lock() + quota := u.Cfg.DataQuotaBytes + action := normalizeQuotaAction(u.Cfg.QuotaAction) + u.mu.Unlock() + return quota > 0 && action == quotaActionBlock && atomic.LoadInt64(&u.totalBytes) >= quota +} + +func sshQuotaLimiter(u *UserState, mbps int) *rate.Limiter { + mbps = quotaThrottleMbpsOrDefault(mbps) + u.mu.Lock() + defer u.mu.Unlock() + if u.quotaLimiter == nil || u.quotaLimiterMbps != mbps { + bps := mbpsToBytesPerSec(mbps) + burst := int(bps) + if burst < copyBufSize { + burst = copyBufSize + } + u.quotaLimiter = rate.NewLimiter(rate.Limit(bps), burst) + u.quotaLimiterMbps = mbps + } + return u.quotaLimiter +} + +func reserveSSHUserBytes(u *UserState, requested int) (allowed int, throttle *rate.Limiter, stopAfter bool) { + if u == nil || requested <= 0 { + return 0, nil, false + } + u.mu.Lock() + quota := u.Cfg.DataQuotaBytes + action := normalizeQuotaAction(u.Cfg.QuotaAction) + throttleMbps := u.Cfg.QuotaThrottleMbps + u.mu.Unlock() + + n := int64(requested) + if quota <= 0 { + atomic.AddInt64(&u.totalBytes, n) + return requested, nil, false + } + + if action == quotaActionThrottle { + previous := atomic.AddInt64(&u.totalBytes, n) - n + if previous+n > quota { + return requested, sshQuotaLimiter(u, throttleMbps), false + } + return requested, nil, false + } + + for { + used := atomic.LoadInt64(&u.totalBytes) + remaining := quota - used + if remaining <= 0 { + return 0, nil, true + } + take := n + if take > remaining { + take = remaining + } + if atomic.CompareAndSwapInt64(&u.totalBytes, used, used+take) { + return int(take), nil, take < n || used+take >= quota + } + } +} + +func finishSSHUserReservation(u *UserState, uplink bool, reserved, written int) { + if u == nil || reserved <= 0 { + return + } + if written < 0 { + written = 0 + } + if written > reserved { + written = reserved + } + if written < reserved { + atomic.AddInt64(&u.totalBytes, -int64(reserved-written)) + } + if written == 0 { + return + } + if uplink { + atomic.AddInt64(&u.TotalUplinkBytes, int64(written)) + atomic.AddInt64(&u.pendingUplinkBytes, int64(written)) + } else { + atomic.AddInt64(&u.TotalDownlinkBytes, int64(written)) + atomic.AddInt64(&u.pendingDownlinkBytes, int64(written)) + } + markSSHUserTrafficDirty(u) +} + +type sshQuotaWriter struct { + w io.Writer + user *UserState + uplink bool + ctx context.Context +} + +func (qw sshQuotaWriter) Write(p []byte) (int, error) { + if qw.user != nil { + qw.user.trafficMu.RLock() + defer qw.user.trafficMu.RUnlock() + } + allowed, quotaLimiter, stopAfter := reserveSSHUserBytes(qw.user, len(p)) + if allowed <= 0 { + return 0, errDataQuotaExceeded + } + if quotaLimiter != nil { + ctx := qw.ctx + if ctx == nil { + ctx = context.Background() + } + if err := quotaLimiter.WaitN(ctx, allowed); err != nil { + finishSSHUserReservation(qw.user, qw.uplink, allowed, 0) + return 0, err + } + } + n, err := qw.w.Write(p[:allowed]) + finishSSHUserReservation(qw.user, qw.uplink, allowed, n) + if err != nil { + return n, err + } + if stopAfter || allowed < len(p) { + return n, errDataQuotaExceeded + } + return n, nil +} + +func startSSHUserTrafficFlusher(store *Store) { + if store == nil { + return + } + go func() { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for range ticker.C { + flushSSHUserTraffic(store) + } + }() +} + +func flushSSHUserTraffic(store *Store) { + if store == nil { + return + } + sshTrafficPersistenceMu.Lock() + defer sshTrafficPersistenceMu.Unlock() + deltas := make(map[string]sshTrafficDelta) + states := make(map[string]*UserState) + for username, u := range takeSSHUserTrafficDirty() { + if u == nil || strings.TrimSpace(username) == "" { + continue + } + up := atomic.SwapInt64(&u.pendingUplinkBytes, 0) + down := atomic.SwapInt64(&u.pendingDownlinkBytes, 0) + if up == 0 && down == 0 { + continue + } + deltas[username] = sshTrafficDelta{Uplink: up, Downlink: down} + states[username] = u + } + if len(deltas) == 0 { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := store.AddSSHUserTrafficBatch(ctx, deltas); err != nil { + log.Printf("ssh traffic flush failed: %v", err) + for username, d := range deltas { + if u := states[username]; u != nil { + atomic.AddInt64(&u.pendingUplinkBytes, d.Uplink) + atomic.AddInt64(&u.pendingDownlinkBytes, d.Downlink) + markSSHUserTrafficDirty(u) + } + } + } +} + +func validateQuotaConfig(quotaBytes int64, action string, throttleMbps int) error { + if quotaBytes < 0 { + return fmt.Errorf("data_quota_bytes must be non-negative") + } + rawAction := strings.ToLower(strings.TrimSpace(action)) + if rawAction != "" && rawAction != quotaActionBlock && rawAction != quotaActionThrottle { + return fmt.Errorf("quota_action must be block or throttle") + } + if throttleMbps < 0 { + return fmt.Errorf("quota_throttle_mbps must be non-negative") + } + if throttleMbps > 1000000 { + return fmt.Errorf("quota_throttle_mbps must not exceed 1000000") + } + return nil +} diff --git a/quota_hardening_test.go b/quota_hardening_test.go new file mode 100644 index 0000000..04f5510 --- /dev/null +++ b/quota_hardening_test.go @@ -0,0 +1,870 @@ +package main + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/time/rate" +) + +func TestNativeClientMaxConnectionsAndBatchedActiveDelta(t *testing.T) { + oldStore := statsStore + statsStore = &Store{} + defer func() { statsStore = oldStore }() + + const uuid = "11111111-1111-1111-1111-111111111111" + m := &XrayManager{ + nativeQuotaByUUID: map[string]*xrayNativeQuotaState{ + uuid: {maxConns: 1, generation: 1}, + }, + } + state := m.nativeQuotaState(uuid) + + release, acquiredState, ok := m.acquireNativeClientConnection(uuid, "user@example") + if !ok || release == nil { + t.Fatal("first native connection was rejected") + } + if acquiredState != state { + t.Fatal("connection lease did not retain the authenticated policy state") + } + if _, _, ok := m.acquireNativeClientConnection(uuid, "user@example"); ok { + t.Fatal("connection above max_conns was accepted") + } + + m.nativeDBMu.Lock() + pending := m.nativeActivePending[uuid] + m.nativeDBMu.Unlock() + if pending.Delta != 1 || !pending.Connected || pending.State != state { + t.Fatalf("connect was not queued for batch persistence: %+v", pending) + } + + release() + release() // idempotent release must not underflow counters. + + m.nativeDBMu.Lock() + pending = m.nativeActivePending[uuid] + m.nativeDBMu.Unlock() + if pending.Delta != 0 || !pending.Connected { + t.Fatalf("connect/disconnect batch should net to zero and retain last-active: %+v", pending) + } + + state.mu.Lock() + active := state.activeConns + state.mu.Unlock() + if active != 0 { + t.Fatalf("active connection count = %d, want 0", active) + } + + release2, _, ok := m.acquireNativeClientConnection(uuid, "user@example") + if !ok { + t.Fatal("slot was not reusable after release") + } + release2() +} + +func TestNativeOnlineUsersAreKeyedByUUID(t *testing.T) { + oldStore := statsStore + statsStore = nil + defer func() { statsStore = oldStore }() + + m := &XrayManager{} + m.recordNativeConnect("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "shared@example", nil) + m.recordNativeConnect("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "shared@example", nil) + if got := m.CountOnlineUsers(); got != 2 { + t.Fatalf("online UUID count = %d, want 2 for two UUIDs sharing one email", got) + } + m.statsMu.RLock() + _, first := m.statsByEmail["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"] + _, second := m.statsByEmail["bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"] + m.statsMu.RUnlock() + if !first || !second { + t.Fatal("native runtime stats were not stored under canonical UUID keys") + } +} + +func TestNativeExpiryRejectsAndDisconnectsClient(t *testing.T) { + const uuid = "cccccccc-cccc-cccc-cccc-cccccccccccc" + state := &xrayNativeQuotaState{hasExpiry: true, expiresAt: time.Now().Add(time.Hour), generation: 1} + m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: state}} + closer := &closeTrackingReader{} + release, _, ok := m.acquireNativeClientConnection(uuid, "expiry@example", closer) + if !ok { + t.Fatal("unexpired client was rejected") + } + m.disconnectNativeClient(uuid) + if !closer.closed.Load() { + t.Fatal("active native client was not closed during revocation") + } + release() + + state.mu.Lock() + state.expiresAt = time.Now().Add(-time.Second) + state.mu.Unlock() + if reason := m.nativeClientAccessDenied(uuid); reason != "expired" { + t.Fatalf("expired client denial = %q, want expired", reason) + } + if _, _, ok := m.acquireNativeClientConnection(uuid, "expiry@example"); ok { + t.Fatal("expired client acquired a new connection") + } +} + +func TestQuotaAndExpiryValidationRejectsUnsafeInput(t *testing.T) { + if err := validateQuotaConfig(1, "typo", 1); err == nil { + t.Fatal("unknown quota action was accepted") + } + if err := validateQuotaConfig(1, quotaActionBlock, -1); err == nil { + t.Fatal("negative throttle setting was accepted") + } + if _, err := parseOptionalXrayExpiry("not-a-date"); err == nil { + t.Fatal("invalid Xray expiry was accepted") + } + if exp, err := parseOptionalXrayExpiry(""); err != nil || exp != nil { + t.Fatalf("empty Xray expiry = (%v, %v), want nil, nil", exp, err) + } +} + +func TestRemoveNativeQuotaPolicyPrunesPendingMaps(t *testing.T) { + m := &XrayManager{ + nativeQuotaByUUID: map[string]*xrayNativeQuotaState{ + "gone": {generation: 1}, + }, + nativeTrafficPending: map[string]xrayPendingTraffic{ + "gone": {Uplink: 10}, + }, + nativeActivePending: map[string]xrayPendingActive{ + "gone": {Delta: 1}, + }, + } + m.removeNativeQuotaPolicy("gone") + if m.nativeQuotaState("gone") != nil { + t.Fatal("quota policy was not removed") + } + m.nativeDBMu.Lock() + _, trafficExists := m.nativeTrafficPending["gone"] + _, activeExists := m.nativeActivePending["gone"] + m.nativeDBMu.Unlock() + if trafficExists || activeExists { + t.Fatal("deleted UUID remained in a pending persistence map") + } +} + +func TestNativeCounterIsBoundedAndReleaseIsIdempotent(t *testing.T) { + var active atomicInt64ForTest + release1, ok := acquireNativeCounter(&active.Int64, 2) + if !ok { + t.Fatal("first slot rejected") + } + release2, ok := acquireNativeCounter(&active.Int64, 2) + if !ok { + t.Fatal("second slot rejected") + } + if _, ok := acquireNativeCounter(&active.Int64, 2); ok { + t.Fatal("slot above limit accepted") + } + release1() + release1() + if got := active.Load(); got != 1 { + t.Fatalf("active after double release = %d, want 1", got) + } + release2() + if got := active.Load(); got != 0 { + t.Fatalf("active after releases = %d, want 0", got) + } +} + +// Embedding keeps the test declaration readable while still passing the exact +// atomic.Int64 type required by acquireNativeCounter. +type atomicInt64ForTest struct{ Int64 atomic.Int64 } + +func (a *atomicInt64ForTest) Load() int64 { return a.Int64.Load() } + +func TestTrackedNativeConnectionsAreClosedOnShutdown(t *testing.T) { + oldAccepting := nativeTransportAccepting.Load() + defer nativeTransportAccepting.Store(oldAccepting) + + beginNativeTransportAccepting() + before := nativeTransportConnections.Load() + serverSide, clientSide := net.Pipe() + defer clientSide.Close() + wrapped, ok := wrapTrackedNativeTransportConn(serverSide) + if !ok { + t.Fatal("tracked connection was rejected") + } + if got := nativeTransportConnections.Load(); got != before+1 { + t.Fatalf("transport count = %d, want %d", got, before+1) + } + + stopNativeTransportAccepting() + closeAllNativeTransportConnections() + _ = clientSide.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := clientSide.Read(make([]byte, 1)); err == nil { + t.Fatal("peer remained open after native shutdown") + } + if err := wrapped.Close(); err != nil && !errors.Is(err, net.ErrClosed) { + t.Fatalf("second close returned unexpected error: %v", err) + } + if got := nativeTransportConnections.Load(); got != before { + t.Fatalf("transport count after shutdown = %d, want %d", got, before) + } +} + +func TestXHTTPSessionsIgnoreLegacyGlobalCapAndReleaseCounters(t *testing.T) { + before := nativeXHTTPSessions.Load() + ib := &nativeInbound{xhttpMaxBufferedPosts: 2} + for _, id := range []string{"one", "two"} { + if sess := ib.upsertXHTTPSession(httptest.NewRecorder(), id); sess == nil { + t.Fatalf("session %q was rejected", id) + } + } + if got := nativeXHTTPSessions.Load(); got != before+2 { + t.Fatalf("global XHTTP sessions = %d, want %d", got, before+2) + } + ib.closeAllXHTTPSessions() + if got := nativeXHTTPSessions.Load(); got != before { + t.Fatalf("global XHTTP sessions after close = %d, want %d", got, before) + } + ib.xhttpMu.Lock() + remaining := len(ib.xhttpSessions) + ib.xhttpMu.Unlock() + if remaining != 0 { + t.Fatalf("inbound retained %d XHTTP sessions", remaining) + } +} + +func TestXHTTPSessionSafetyWindowIsAboveProductionScale(t *testing.T) { + if got := (&nativeInbound{}).xhttpMaxActiveSessions(); got != fixedNativeMaxXHTTPSessions { + t.Fatalf("XHTTP session safety window = %d, want %d", got, fixedNativeMaxXHTTPSessions) + } + if got := nativeXHTTPSessionLimit(); got < 8_000 { + t.Fatalf("XHTTP session safety window = %d, want room for at least 8K users", got) + } +} + +func TestNativeHTTP2StreamsUseFiniteTransportBackpressure(t *testing.T) { + if got := nativeHTTP2MaxConcurrentStreams(); got != fixedNativeHTTP2ConcurrentStreams { + t.Fatalf("HTTP/2 stream setting = %d, want %d", got, fixedNativeHTTP2ConcurrentStreams) + } + if got := nativeHTTP2MaxConcurrentStreams(); got < 1024 { + t.Fatalf("HTTP/2 stream setting = %d, too small for XHTTP packet bursts", got) + } + if got := nativeMuxMaxSessionLimit(); got != 64 { + t.Fatalf("per-transport Mux session guard = %d, want 64", got) + } +} + +func TestXHTTPHandlerDoesNotApplyWebRequestCeiling(t *testing.T) { + ib := &nativeInbound{transport: "xhttp", path: "/"} + req := httptest.NewRequest(http.MethodOptions, "/", nil) + rec := httptest.NewRecorder() + ib.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("XHTTP OPTIONS at legacy request ceiling = %d, want 200", rec.Code) + } +} + +func TestXHTTPHandlerSafetySlotIsReleased(t *testing.T) { + before := nativeXHTTPRequests.Load() + ib := &nativeInbound{transport: "xhttp", path: "/"} + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + ib.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("empty XHTTP request status = %d, want 400", rec.Code) + } + if got := nativeXHTTPRequests.Load(); got != before { + t.Fatalf("XHTTP handler counter after return = %d, want %d", got, before) + } +} + +func TestPersistedXHTTPAdmissionTuningIsAlwaysUnlimited(t *testing.T) { + got := normalizeNativeXrayTuning(&XrayNativeTuning{ + MuxGlobalSessions: 8192, + MaxConcurrentConnections: 4096, + MaxConcurrentXHTTPRequests: 8192, + XHTTPMaxSessions: 4096, + }) + if got.MuxGlobalSessions != 8192 || + got.MaxConcurrentConnections != -1 || + got.MaxConcurrentXHTTPRequests != defaultNativeMaxXHTTPRequests || + got.XHTTPMaxSessions != -1 { + t.Fatalf("persisted admission limits were not removed: %+v", got) + } +} + +func TestXHTTPMetadataLengthIsBoundedBeforeSessionAllocation(t *testing.T) { + ib := &nativeInbound{transport: "xhttp", path: "/"} + req := httptest.NewRequest("GET", "/"+strings.Repeat("a", nativeXHTTPMaxSessionIDBytes+1), nil) + rec := httptest.NewRecorder() + ib.ServeHTTP(rec, req) + if rec.Code != 400 { + t.Fatalf("oversized XHTTP session id status = %d, want 400", rec.Code) + } + ib.xhttpMu.Lock() + sessions := len(ib.xhttpSessions) + ib.xhttpMu.Unlock() + if sessions != 0 { + t.Fatalf("oversized metadata allocated %d sessions", sessions) + } +} + +func TestXHTTPUploadMemoryIsReleasedOnReadAndClose(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + q := newNativeXHTTPUploadQueue(4, 512) + + accounted := nativeXHTTPAccountedPacketBytes(4) + lease, ok := acquireNativeXHTTPMemory(accounted) + if !ok { + t.Fatal("failed to reserve XHTTP test memory") + } + if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("test"), Seq: 0}, lease); err != nil { + lease.release() + t.Fatalf("queue push failed: %v", err) + } + lease.release() // transferred leases are a no-op for the producer. + if got := nativeXHTTPBufferedBytes.Load(); got != before+accounted { + t.Fatalf("buffered bytes after push = %d, want %d", got, before+accounted) + } + + buf := make([]byte, 4) + if n, err := q.Read(buf); err != nil || n != 4 || string(buf) != "test" { + t.Fatalf("queue read = (%d, %v, %q), want (4, nil, test)", n, err, string(buf)) + } + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("buffered bytes after read = %d, want %d", got, before) + } + + lease, ok = acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(3)) + if !ok { + t.Fatal("failed to reserve second XHTTP test memory") + } + if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("xyz"), Seq: 2}, lease); err != nil { + lease.release() + t.Fatalf("second queue push failed: %v", err) + } + lease.release() + q.close() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("buffered bytes after close = %d, want %d", got, before) + } +} + +func TestXHTTPUploadQueueEnforcesPerSessionByteBudget(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + q := newNativeXHTTPUploadQueue(4, nativeXHTTPMinPacketAccountingBytes-1) + defer q.close() + + lease, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(5)) + if !ok { + t.Fatal("failed to reserve XHTTP test memory") + } + defer lease.release() + err := q.push(context.Background(), nativeXHTTPPacket{Payload: make([]byte, 5)}, lease) + if !errors.Is(err, errNativeXHTTPUploadBufferFull) { + t.Fatalf("oversized queue push error = %v, want buffer limit", err) + } + lease.release() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("rejected payload retained %d bytes, baseline %d", got, before) + } +} + +func TestXHTTPUploadQueueBackpressuresInsteadOfRejectingBurst(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + q := newNativeXHTTPUploadQueue(2, nativeXHTTPMinPacketAccountingBytes) + defer q.close() + + first, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(4)) + if !ok { + t.Fatal("failed to reserve first XHTTP payload") + } + if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("one!"), Seq: 0}, first); err != nil { + first.release() + t.Fatalf("first queue push failed: %v", err) + } + first.release() + + second, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(4)) + if !ok { + t.Fatal("failed to reserve second XHTTP payload") + } + done := make(chan error, 1) + go func() { + done <- q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("two!"), Seq: 1}, second) + }() + + select { + case err := <-done: + second.release() + t.Fatalf("second burst packet did not backpressure: %v", err) + case <-time.After(25 * time.Millisecond): + } + + buf := make([]byte, 4) + if n, err := q.Read(buf); err != nil || n != 4 || string(buf) != "one!" { + second.release() + t.Fatalf("first queue read = (%d, %v, %q)", n, err, string(buf)) + } + select { + case err := <-done: + if err != nil { + second.release() + t.Fatalf("backpressured packet failed after space released: %v", err) + } + second.release() + case <-time.After(time.Second): + second.release() + t.Fatal("backpressured packet did not resume") + } + + q.close() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("backpressure test leaked %d buffered bytes (baseline %d)", got, before) + } +} + +func TestXHTTPGlobalMemoryBackpressureWakesWaitersFIFO(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + fillBytes := nativeXHTTPMaxBufferedGlobalBytes - before + filler, ok := acquireNativeXHTTPMemory(fillBytes) + if !ok { + t.Fatal("failed to fill XHTTP memory budget for waiter test") + } + defer filler.release() + + type result struct { + lease *nativeXHTTPMemoryLease + err error + } + startWaiter := func() <-chan result { + done := make(chan result, 1) + go func() { + lease, err := acquireNativeXHTTPMemoryContext(context.Background(), nativeXHTTPMinPacketAccountingBytes) + done <- result{lease: lease, err: err} + }() + return done + } + waitForWaiters := func(want int) { + t.Helper() + deadline := time.Now().Add(time.Second) + for { + nativeXHTTPMemoryWait.Lock() + got := nativeXHTTPMemoryWait.queued + nativeXHTTPMemoryWait.Unlock() + if got == want { + return + } + if time.Now().After(deadline) { + t.Fatalf("memory waiters = %d, want %d", got, want) + } + time.Sleep(time.Millisecond) + } + } + + firstDone := startWaiter() + waitForWaiters(1) + secondDone := startWaiter() + waitForWaiters(2) + + filler.shrink(fillBytes - nativeXHTTPMinPacketAccountingBytes) + first := <-firstDone + if first.err != nil || first.lease == nil { + t.Fatalf("first memory waiter = (%v, %v)", first.lease, first.err) + } + select { + case second := <-secondDone: + if second.lease != nil { + second.lease.release() + } + t.Fatalf("second waiter woke before FIFO capacity was released: %v", second.err) + case <-time.After(25 * time.Millisecond): + } + + first.lease.release() + select { + case second := <-secondDone: + if second.err != nil || second.lease == nil { + t.Fatalf("second memory waiter = (%v, %v)", second.lease, second.err) + } + second.lease.release() + case <-time.After(time.Second): + t.Fatal("second memory waiter did not wake after first released") + } + + filler.release() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("FIFO waiter test leaked %d buffered bytes (baseline %d)", got, before) + } +} + +func TestXHTTPReassemblyHasNoPacketRequestCountCeiling(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + q := newNativeXHTTPUploadQueue(1, 4*nativeXHTTPMinPacketAccountingBytes) + defer q.close() + + done := make(chan error, 1) + go func() { + for _, seq := range []uint64{3, 2, 1, 0} { + lease, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(1)) + if !ok { + done <- errors.New("could not reserve packet memory") + return + } + err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte{byte('a' + seq)}, Seq: seq}, lease) + lease.release() + if err != nil { + done <- err + return + } + } + done <- nil + }() + + buf := make([]byte, 1) + for want := byte('a'); want <= byte('d'); want++ { + n, err := q.Read(buf) + if err != nil || n != 1 || buf[0] != want { + t.Fatalf("reassembled packet = (%d, %v, %q), want %q", n, err, buf[:n], []byte{want}) + } + } + if err := <-done; err != nil { + t.Fatalf("out-of-order burst was rejected: %v", err) + } + q.close() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("reassembly test leaked %d buffered bytes (baseline %d)", got, before) + } +} + +func TestXHTTPBodyReservationUsesActualContentLength(t *testing.T) { + ib := &nativeInbound{xhttpMaxEachPostBytes: 1_000_000} + req := httptest.NewRequest(http.MethodPost, "/session/0", strings.NewReader("small")) + if got := ib.xhttpUploadReservationBytes(req); got != nativeXHTTPMinPacketAccountingBytes { + t.Fatalf("body reservation = %d, want minimum accounted packet size", got) + } + req.ContentLength = -1 + if got := ib.xhttpUploadReservationBytes(req); got != 1_000_000 { + t.Fatalf("chunked body reservation = %d, want configured maximum", got) + } +} + +func TestNativeQuotaResetWaitsForInFlightTraffic(t *testing.T) { + const uuid = "22222222-2222-2222-2222-222222222222" + state := &xrayNativeQuotaState{usedBytes: 123, generation: 1} + m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: state}} + + state.trafficMu.RLock() + done := make(chan struct{}) + go func() { + m.resetNativeQuotaUsage(uuid) + close(done) + }() + select { + case <-done: + state.trafficMu.RUnlock() + t.Fatal("traffic reset crossed an in-flight writer boundary") + case <-time.After(25 * time.Millisecond): + } + state.trafficMu.RUnlock() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("traffic reset did not complete after writer released") + } + state.mu.Lock() + used, generation := state.usedBytes, state.generation + state.mu.Unlock() + if used != 0 || generation != 2 { + t.Fatalf("reset state = used %d generation %d, want 0/2", used, generation) + } +} + +func TestNativeRateWaitCanBeCanceled(t *testing.T) { + lim := rate.NewLimiter(1, 1) + if !lim.AllowN(time.Now(), 1) { + t.Fatal("failed to consume initial limiter token") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := waitNativeRate(ctx, lim, 1); !errors.Is(err, context.Canceled) { + t.Fatalf("waitNativeRate error = %v, want context.Canceled", err) + } +} + +func TestSSHDirtyQueueDoesNotScanInactiveUsers(t *testing.T) { + sshTrafficDirtyMu.Lock() + old := sshTrafficDirty + sshTrafficDirty = make(map[string]*UserState) + sshTrafficDirtyMu.Unlock() + defer func() { + sshTrafficDirtyMu.Lock() + sshTrafficDirty = old + sshTrafficDirtyMu.Unlock() + }() + + active := &UserState{Cfg: UserConfig{Username: "active"}} + inactive := &UserState{Cfg: UserConfig{Username: "inactive"}} + markSSHUserTrafficDirty(active) + dirty := takeSSHUserTrafficDirty() + if len(dirty) != 1 || dirty["active"] != active { + t.Fatalf("dirty queue = %#v", dirty) + } + if _, found := dirty[inactive.Cfg.Username]; found { + t.Fatal("inactive user appeared in dirty queue") + } + if next := takeSSHUserTrafficDirty(); len(next) != 0 { + t.Fatalf("dirty queue was not drained: %#v", next) + } +} + +func TestOldNativeConnectionCannotDecrementReplacementAccount(t *testing.T) { + oldStore := statsStore + statsStore = &Store{} + defer func() { statsStore = oldStore }() + + const uuid = "replacement-active-user" + oldState := &xrayNativeQuotaState{maxConns: 1, generation: 1} + m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: oldState}} + + release, acquiredState, ok := m.acquireNativeClientConnection(uuid, "old@example") + if !ok || acquiredState != oldState { + t.Fatal("failed to acquire old account connection") + } + // Discard the old account's successful connect delta so this assertion only + // measures what happens when that old connection later disconnects. + m.nativeDBMu.Lock() + m.nativeActivePending = nil + m.nativeDBMu.Unlock() + + newState := &xrayNativeQuotaState{maxConns: 1, generation: 1} + m.nativeQuotaMu.Lock() + m.nativeQuotaByUUID[uuid] = newState + m.nativeQuotaMu.Unlock() + + release() + + m.nativeDBMu.Lock() + pending := m.nativeActivePending[uuid] + m.nativeDBMu.Unlock() + if pending.Delta != 0 || pending.State != nil { + t.Fatalf("old disconnect was queued against replacement account: %+v", pending) + } + newState.mu.Lock() + active := newState.activeConns + newState.mu.Unlock() + if active != 0 { + t.Fatalf("replacement account active count changed to %d", active) + } +} + +func TestOldNativeTrafficCannotAttachToReplacementAccount(t *testing.T) { + oldStore := statsStore + statsStore = &Store{} + defer func() { statsStore = oldStore }() + + const uuid = "replacement-traffic-user" + oldState := &xrayNativeQuotaState{generation: 1} + newState := &xrayNativeQuotaState{generation: 1} + m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: oldState}} + + meter := newTrafficMeter(uuid, "old@example", true, oldState) + meter.n = 1234 + + m.nativeQuotaMu.Lock() + m.nativeQuotaByUUID[uuid] = newState + m.nativeQuotaMu.Unlock() + + oldMgr := xrayMgr + xrayMgr = m + defer func() { xrayMgr = oldMgr }() + meter.flush() + + m.nativeDBMu.Lock() + pending := m.nativeTrafficPending[uuid] + m.nativeDBMu.Unlock() + if pending.Uplink != 0 || pending.Downlink != 0 || pending.State != nil { + t.Fatalf("old traffic was queued against replacement account: %+v", pending) + } + m.statsMu.RLock() + stat := m.statsByEmail["old@example"] + m.statsMu.RUnlock() + if stat.Uplink != 0 || stat.Downlink != 0 { + t.Fatalf("old traffic resurfaced in runtime stats: %+v", stat) + } +} + +func TestNativeFlusherDropsMismatchedPolicyIdentity(t *testing.T) { + oldStore := statsStore + statsStore = &Store{} + defer func() { statsStore = oldStore }() + + const uuid = "identity-prune-user" + oldState := &xrayNativeQuotaState{generation: 1} + newState := &xrayNativeQuotaState{generation: 1} + m := &XrayManager{ + nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: newState}, + nativeTrafficPending: map[string]xrayPendingTraffic{ + uuid: {Email: "old@example", Uplink: 99, State: oldState}, + }, + nativeActivePending: map[string]xrayPendingActive{ + uuid: {Email: "old@example", Delta: -1, State: oldState}, + }, + } + m.flushNativeStatsToDB() + + m.nativeDBMu.Lock() + defer m.nativeDBMu.Unlock() + if len(m.nativeTrafficPending) != 0 || len(m.nativeActivePending) != 0 { + t.Fatalf("mismatched pending deltas survived prune: traffic=%v active=%v", m.nativeTrafficPending, m.nativeActivePending) + } +} + +func TestNativeMuxFinishRunsOnce(t *testing.T) { + var calls atomic.Int32 + s := &nativeMuxSession{ + closed: make(chan struct{}), + uplink: make(chan nativeMuxUplinkItem), + onClose: func(*nativeMuxSession) { + calls.Add(1) + }, + } + + var wg sync.WaitGroup + for i := 0; i < 32; i++ { + wg.Add(1) + go func() { + defer wg.Done() + s.finish() + }() + } + wg.Wait() + if got := calls.Load(); got != 1 { + t.Fatalf("mux onClose called %d times, want 1", got) + } +} + +type closeTrackingReader struct { + closed atomic.Bool +} + +func (r *closeTrackingReader) Read([]byte) (int, error) { return 0, io.EOF } +func (r *closeTrackingReader) Close() error { + r.closed.Store(true) + return nil +} + +func TestNativeXHTTPQueueCloseClosesQueuedStreamReader(t *testing.T) { + q := newNativeXHTTPUploadQueue(1, 1024) + r := &closeTrackingReader{} + if err := q.push(context.Background(), nativeXHTTPPacket{Reader: r}, nil); err != nil { + t.Fatalf("queue stream reader: %v", err) + } + q.close() + if !r.closed.Load() { + t.Fatal("queued stream reader was not closed during queue shutdown") + } +} + +func TestNativeXHTTPQueueSkipsEmptyPacketsWithoutZeroProgressRead(t *testing.T) { + before := nativeXHTTPBufferedBytes.Load() + q := newNativeXHTTPUploadQueue(2, 2*nativeXHTTPMinPacketAccountingBytes) + defer q.close() + + for seq, payload := range [][]byte{nil, []byte("x")} { + accounted := nativeXHTTPAccountedPacketBytes(int64(len(payload))) + lease, ok := acquireNativeXHTTPMemory(accounted) + if !ok { + t.Fatal("failed to reserve packet memory") + } + if err := q.push(context.Background(), nativeXHTTPPacket{Payload: payload, Seq: uint64(seq)}, lease); err != nil { + lease.release() + t.Fatalf("queue packet %d: %v", seq, err) + } + lease.release() + } + + buf := make([]byte, 1) + n, err := q.Read(buf) + if err != nil || n != 1 || string(buf[:n]) != "x" { + t.Fatalf("queue read after empty packet = (%d, %v, %q), want (1, nil, x)", n, err, buf[:n]) + } + q.close() + if got := nativeXHTTPBufferedBytes.Load(); got != before { + t.Fatalf("empty-packet test leaked %d buffered bytes (baseline %d)", got, before) + } +} + +type deadlineUnblockingResponseWriter struct { + header http.Header + writeStart chan struct{} + unblock chan struct{} + startOnce sync.Once + unblockOnce sync.Once +} + +func newDeadlineUnblockingResponseWriter() *deadlineUnblockingResponseWriter { + return &deadlineUnblockingResponseWriter{ + header: make(http.Header), + writeStart: make(chan struct{}), + unblock: make(chan struct{}), + } +} + +func (w *deadlineUnblockingResponseWriter) Header() http.Header { return w.header } +func (w *deadlineUnblockingResponseWriter) WriteHeader(int) {} +func (w *deadlineUnblockingResponseWriter) Flush() {} +func (w *deadlineUnblockingResponseWriter) Write([]byte) (int, error) { + w.startOnce.Do(func() { close(w.writeStart) }) + <-w.unblock + return 0, os.ErrDeadlineExceeded +} +func (w *deadlineUnblockingResponseWriter) SetWriteDeadline(deadline time.Time) error { + if !deadline.IsZero() && !deadline.After(time.Now().Add(10*time.Millisecond)) { + w.unblockOnce.Do(func() { close(w.unblock) }) + } + return nil +} + +func TestNativeXHTTPResponseCloseInterruptsStalledWrite(t *testing.T) { + underlying := newDeadlineUnblockingResponseWriter() + writer := newNativeXHTTPResponseWriter(underlying) + writeDone := make(chan error, 1) + go func() { + _, err := writer.Write([]byte("blocked")) + writeDone <- err + }() + + select { + case <-underlying.writeStart: + case <-time.After(time.Second): + t.Fatal("response write did not start") + } + + closeDone := make(chan struct{}) + go func() { + writer.close() + close(closeDone) + }() + select { + case <-closeDone: + case <-time.After(time.Second): + t.Fatal("response close blocked behind stalled write") + } + select { + case err := <-writeDone: + if !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("stalled write error = %v, want deadline exceeded", err) + } + case <-time.After(time.Second): + t.Fatal("stalled response write was not interrupted") + } +} diff --git a/security_hardening_test.go b/security_hardening_test.go new file mode 100644 index 0000000..081b97e --- /dev/null +++ b/security_hardening_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "testing" + "time" +) + +func TestAdminPasswordHashAndLegacyUpgrade(t *testing.T) { + password := "correct-horse-battery-staple" + hash, err := hashAdminPassword(password) + if err != nil { + t.Fatal(err) + } + if valid, upgrade := verifyAdminPassword(hash, password); !valid || upgrade { + t.Fatalf("bcrypt verification = valid %v, upgrade %v", valid, upgrade) + } + if valid, _ := verifyAdminPassword(hash, "wrong-password"); valid { + t.Fatal("wrong bcrypt password was accepted") + } + legacy := legacyAdminPasswordHash(password) + if valid, upgrade := verifyAdminPassword(legacy, password); !valid || !upgrade { + t.Fatalf("legacy verification = valid %v, upgrade %v", valid, upgrade) + } +} + +func TestTLSDomainRejectsTraversal(t *testing.T) { + for _, value := range []string{"../root", `..\\root`, "/absolute", "host\nname"} { + if _, _, err := normalizeTLSDomain(value, true); err == nil { + t.Fatalf("normalizeTLSDomain(%q) accepted unsafe value", value) + } + } + if domain, _, err := normalizeTLSDomain("vpn.example.com", false); err != nil || domain != "vpn.example.com" { + t.Fatalf("valid domain rejected: %q, %v", domain, err) + } +} + +func TestManagedServerURLValidation(t *testing.T) { + for _, value := range []string{ + "ftp://example.com", "https://user:pass@example.com", "https://example.com/admin", "http://169.254.10.20", + } { + if _, err := validateManagedServerBaseURL(value); err == nil { + t.Fatalf("validateManagedServerBaseURL(%q) accepted unsafe value", value) + } + } + if got, err := validateManagedServerBaseURL("https://node.example.com/"); err != nil || got != "https://node.example.com" { + t.Fatalf("valid managed server URL = %q, %v", got, err) + } +} + +func TestMPSignatureRequiresSecretAndValidHMAC(t *testing.T) { + const ( + secret = "test-secret-with-enough-entropy" + dataID = "123456789" + requestID = "request-123" + ) + ts := time.Now().Format("150405") + manifest := "id:" + dataID + ";request-id:" + requestID + ";ts:" + ts + ";" + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write([]byte(manifest)) + signature := "ts=" + ts + ",v1=" + hex.EncodeToString(mac.Sum(nil)) + if !verifyMPSignature(signature, requestID, dataID, secret) { + t.Fatal("valid Mercado Pago signature was rejected") + } + if verifyMPSignature(signature, requestID, dataID, "") { + t.Fatal("unsigned webhook mode was accepted") + } + if verifyMPSignature(signature, requestID, dataID, "wrong-secret") { + t.Fatal("signature with wrong secret was accepted") + } +} diff --git a/security_http.go b/security_http.go new file mode 100644 index 0000000..f461c96 --- /dev/null +++ b/security_http.go @@ -0,0 +1,59 @@ +package main + +import ( + "fmt" + "net/http" + "os" + "path/filepath" +) + +const maxAPIRequestBody = 8 << 20 + +// secureAPIHandler applies baseline HTTP protections and a global request +// body ceiling. Endpoint-specific handlers may impose a smaller limit. +func secureAPIHandler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()") + w.Header().Set("Cross-Origin-Opener-Policy", "same-origin") + w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'; form-action 'self'; img-src 'self' data:; connect-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'") + w.Header().Set("Cache-Control", "no-store") + if r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead { + r.Body = http.MaxBytesReader(w, r.Body, maxAPIRequestBody) + } + next.ServeHTTP(w, r) + }) +} + +// writeFileAtomic replaces a sensitive configuration file without leaving a +// partially written file behind after a crash or interrupted request. +func writeFileAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + tmp, err := os.CreateTemp(dir, ".dragoncore-*.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + if err := tmp.Chmod(mode); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("replace %s: %w", path, err) + } + return nil +} diff --git a/server_config_api.go b/server_config_api.go new file mode 100644 index 0000000..e3f8971 --- /dev/null +++ b/server_config_api.go @@ -0,0 +1,159 @@ +package main + +import ( + "encoding/json" + "io" + "net/http" + "os" + "sync" +) + +// Note: applyFullConfigReload is defined in hotreload.go + +// ---------- Global config holder ---------- + +var ( + globalCfgMu sync.RWMutex + globalCfg *Config + globalCfgPath string // set in main() from the -config flag + + bannerMu sync.RWMutex + currentBannerText string +) + +func setGlobalCfg(c *Config) { + globalCfgMu.Lock() + globalCfg = c + globalCfgMu.Unlock() +} + +func getGlobalCfg() *Config { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg +} + +func setBannerText(s string) { + bannerMu.Lock() + currentBannerText = s + bannerMu.Unlock() +} + +func getBannerText() string { + bannerMu.RLock() + defer bannerMu.RUnlock() + return currentBannerText +} + +// ---------- HTTP handler ---------- + +// handleServerConfig dispatches GET (read) and POST (write) for /api/server/config. +func handleServerConfig(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + serverConfigGet(w, r) + case http.MethodPost: + serverConfigPost(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func serverConfigGet(w http.ResponseWriter, _ *http.Request) { + if globalCfgPath == "" { + http.Error(w, "config path not set", http.StatusInternalServerError) + return + } + data, err := os.ReadFile(globalCfgPath) + if err != nil { + http.Error(w, "failed to read config: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(data) +} + +func serverConfigPost(w http.ResponseWriter, r *http.Request) { + if globalCfgPath == "" { + http.Error(w, "config path not set", http.StatusInternalServerError) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, 512*1024+1)) + if err != nil { + http.Error(w, "failed to read body", http.StatusBadRequest) + return + } + if len(body) > 512*1024 { + http.Error(w, "config exceeds 512 KiB", http.StatusRequestEntityTooLarge) + return + } + // Keep track of optional field presence separately from its value. This + // protects a newly-added setting from being reset by a stale cached panel + // bundle that does not know how to send the field yet. For the service + // blocks the distinction matters twice over: a missing key must keep the + // running service, while an explicit null is the panel disabling it. + var fieldPresence struct { + PAMAuthEnabled *bool `json:"pam_auth_enabled"` + BHTTP *json.RawMessage `json:"bhttp"` + BTUN *json.RawMessage `json:"btun"` + HCR *json.RawMessage `json:"hcr"` + } + if err := json.Unmarshal(body, &fieldPresence); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + + var newCfg Config + if err := json.Unmarshal(body, &newCfg); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + if newCfg.Listen == "" { + http.Error(w, "listen address required", http.StatusBadRequest) + return + } + if newCfg.Xray != nil { + newCfg.Xray.NormalizeDefaults() + } + + // Preserve file-based users array (not editable through the UI). + globalCfgMu.RLock() + if globalCfg != nil { + newCfg.Users = globalCfg.Users + if fieldPresence.PAMAuthEnabled == nil { + newCfg.PAMAuthEnabled = globalCfg.PAMAuthEnabled + } + if fieldPresence.BHTTP == nil { + newCfg.BHTTP = globalCfg.BHTTP + } + if fieldPresence.BTUN == nil { + newCfg.BTUN = globalCfg.BTUN + } + if fieldPresence.HCR == nil { + newCfg.HCR = globalCfg.HCR + } + } + globalCfgMu.RUnlock() + + portWarnings := normalizeRuntimePorts(&newCfg) + + out, err := json.MarshalIndent(newCfg, "", " ") + if err != nil { + http.Error(w, "marshal error", http.StatusInternalServerError) + return + } + if err := writeFileAtomic(globalCfgPath, out, 0o600); err != nil { + http.Error(w, "failed to write config: "+err.Error(), http.StatusInternalServerError) + return + } + + // Apply all changes live and return health checks to the panel. + report := applyFullConfigReload(&newCfg) + if len(portWarnings) > 0 { + report.Warnings = append(portWarnings, report.Warnings...) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(report) +} diff --git a/system_logs_api.go b/system_logs_api.go new file mode 100644 index 0000000..535e456 --- /dev/null +++ b/system_logs_api.go @@ -0,0 +1,113 @@ +package main + +import ( + "bufio" + "encoding/json" + "net/http" + "os" + "strconv" + "strings" +) + +const defaultPanelLogFile = "/opt/sshpanel/logs/panel.log" + +type systemLogsResponse struct { + Source string `json:"source"` + Path string `json:"path,omitempty"` + Lines []string `json:"lines"` +} + +func handleSystemLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + limit := 300 + if raw := strings.TrimSpace(r.URL.Query().Get("lines")); raw != "" { + if n, err := strconv.Atoi(raw); err == nil && n > 0 { + limit = n + } + } + if limit > 2000 { + limit = 2000 + } + + source := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("source"))) + if source == "" { + source = "panel" + } + + resp := systemLogsResponse{Source: source, Lines: []string{}} + switch source { + case "dnstt": + resp.Lines = limitLines(getDNSTTLogLines(), limit) + case "xray": + resp.Lines = limitLines(xrayLogBuf.snapshot(), limit) + default: + resp.Source = "panel" + path := panelLogFilePath() + resp.Path = path + lines, err := tailTextFile(path, limit) + if err != nil { + lines = []string{"unable to read " + path + ": " + err.Error()} + } + resp.Lines = lines + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + +func tailTextFile(path string, limit int) ([]string, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + if limit <= 0 { + limit = 300 + } + ring := make([]string, limit) + count := 0 + scanner := bufio.NewScanner(f) + buf := make([]byte, 0, 64*1024) + scanner.Buffer(buf, 1024*1024) + for scanner.Scan() { + ring[count%limit] = scanner.Text() + count++ + } + if err := scanner.Err(); err != nil { + return nil, err + } + if count == 0 { + return []string{}, nil + } + outLen := count + if outLen > limit { + outLen = limit + } + out := make([]string, 0, outLen) + start := 0 + if count > limit { + start = count % limit + } + for i := 0; i < outLen; i++ { + out = append(out, ring[(start+i)%limit]) + } + return out, nil +} + +func limitLines(lines []string, limit int) []string { + if len(lines) == 0 { + return []string{} + } + if limit <= 0 || len(lines) <= limit { + out := make([]string, len(lines)) + copy(out, lines) + return out + } + out := make([]string, limit) + copy(out, lines[len(lines)-limit:]) + return out +} diff --git a/test_dragoncore_cli.py b/test_dragoncore_cli.py new file mode 100644 index 0000000..d5c1325 --- /dev/null +++ b/test_dragoncore_cli.py @@ -0,0 +1,121 @@ +import importlib.util +import io +from pathlib import Path +import tempfile +import unittest +from contextlib import redirect_stdout +from types import SimpleNamespace +from unittest.mock import patch + + +MODULE = Path(__file__).with_name("dragoncore_cli.py") +spec = importlib.util.spec_from_file_location("dragoncore_cli", MODULE) +cli = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cli) + + +class TokenManagementTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + env = Path(self.temp.name) / ".env" + env.write_text("PG_DSN=test\nADMIN_TOKEN=" + "a" * 48 + "\nADMIN_HTTP_ADDR=127.0.0.1:9090\n") + env.chmod(0o600) + self.path = env + patcher = patch.object(cli, "ENV_FILE", env) + patcher.start() + self.addCleanup(patcher.stop) + + def test_rotation_preserves_other_env_and_never_prompts(self): + with patch.object(cli, "service_action") as service, patch.object(cli, "request", return_value=[]): + with patch("builtins.input", side_effect=AssertionError("prompted")): + with redirect_stdout(io.StringIO()): + cli.rotate_api_password() + self.assertNotEqual(cli.api_password(), "a" * 48) + self.assertIn("PG_DSN=test\n", self.path.read_text()) + self.assertEqual(self.path.stat().st_mode & 0o777, 0o600) + service.assert_called_once_with("restart") + + def test_failed_rotation_restores_previous_token(self): + with patch.object(cli, "service_action", side_effect=[None, None]), \ + patch.object(cli, "request", side_effect=cli.CLIError("bad API")), \ + patch.object(cli.time, "sleep"): + with self.assertRaises(cli.CLIError): + cli.rotate_api_password() + self.assertEqual(cli.api_password(), "a" * 48) + + def test_live_vps_header_counts_users_and_rates(self): + responses = [ + {"cpu_percent": 12.5, "mem_total_bytes": 8 * 1024**3, + "mem_used_bytes": 2 * 1024**3, + "interfaces": [{"rx_mbps": 18.5, "tx_mbps": 4.2}]}, + [{"username": "alice", "active_conns": 2, "expires_at": "2099-01-01T00:00:00Z"}, + {"username": "bob", "active_conns": 0, "expires_at": "2020-01-01T00:00:00Z"}], + {"online_users": 3}, + ] + with patch.object(cli, "request", side_effect=responses), \ + patch.object(cli.shutil, "disk_usage", return_value=SimpleNamespace(used=50, total=100)), \ + patch.object(cli.subprocess, "run", return_value=SimpleNamespace(stdout="active\n")): + status = cli.collect_vps_status() + header = cli.render_vps_status(status) + self.assertIn("12.5%", header) + self.assertIn("1 online | 1 expired | 2 total", header) + self.assertIn("Xray: 3 online", header) + self.assertIn("18.50 Mbps", header) + self.assertEqual(len({len(row) for row in header.splitlines()}), 1) + menu_text = cli.render_menu("MAIN MENU", cli.main_menu_options(), status) + self.assertIn("CONNECTION", menu_text.upper()) + self.assertNotIn("Resellers", menu_text) + mobile = cli.render_menu("MAIN MENU", cli.main_menu_options(), status, columns=40) + self.assertLessEqual(max(map(len, mobile.splitlines())), 40) + self.assertIn("CPU: 12.5%", mobile) + self.assertIn("SSH: 1 on / 2 total", mobile) + + def test_user_list_fits_phone_terminal(self): + users = [{"username": "account-with-a-long-name", "active_conns": 2, + "max_connections": 5, "total_bytes": 1234567, + "expires_at": "2099-05-01T12:00:00Z"}] + with patch.object(cli, "request", return_value=users), \ + patch.object(cli, "terminal_columns", return_value=40), \ + redirect_stdout(io.StringIO()) as output: + cli.list_users() + self.assertLessEqual(max(map(len, output.getvalue().splitlines())), 40) + + def test_shared_xray_generates_path_without_password_prompt(self): + server = {"listen": "0.0.0.0:80", "tls_forwarders": [{"listen": "0.0.0.0:443"}], + "xray": {"mode": "native"}} + config = {"inbounds": [{"tag": "first", "protocol": "vless", "dragoncoreSharedPort": True, + "streamSettings": {"network": "ws", "wsSettings": {"path": "/c1"}}}]} + calls = [] + + def fake_request(method, path, data=None): + calls.append((method, path, data)) + if path == "/api/server/config": + return server + if path == "/api/xray/config" and method == "GET": + return config + if path == "/api/xray/status": + return {"running": False} + return None + + # The flow asks only for the tag, transport, path, protocol, and consent. + with patch.object(cli, "request", side_effect=fake_request), \ + patch("builtins.input", side_effect=["second", "", "", "", "YES"]), \ + redirect_stdout(io.StringIO()): + cli.xray_shared_port() + new = config["inbounds"][1] + self.assertEqual(new["streamSettings"]["wsSettings"]["path"], "/c2") + self.assertEqual(new["streamSettings"]["security"], "none") + self.assertTrue(new["dragoncoreSharedPort"]) + self.assertEqual([item[1] for item in calls[-3:]], + ["/api/xray/config", "/api/xray/status", "/api/xray/start"]) + + def test_shared_xray_rejects_external_mode(self): + with patch.object(cli, "request", return_value={"xray": {"mode": "external"}}), \ + patch("builtins.input", side_effect=AssertionError("prompted")): + with self.assertRaisesRegex(cli.CLIError, "native"): + cli.xray_shared_port() + + +if __name__ == "__main__": + unittest.main() diff --git a/tls_api.go b/tls_api.go new file mode 100644 index 0000000..c1a58d9 --- /dev/null +++ b/tls_api.go @@ -0,0 +1,243 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "fmt" + "math/big" + "net" + "net/http" + "net/mail" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" +) + +// tlsCertsDir holds panel-managed certificates. It is a var so tests can point +// it at a temporary directory. +var tlsCertsDir = "/opt/sshpanel/certs" + +var ( + tlsDNSNamePattern = regexp.MustCompile(`^(?:\*\.)?(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`) + tlsStoreNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) +) + +func normalizeTLSDomain(raw string, allowWildcard bool) (domain string, dirName string, err error) { + domain = strings.TrimSuffix(strings.TrimSpace(raw), ".") + if domain == "" || len(domain) > 253 || strings.ContainsAny(domain, "/\\\x00\r\n") { + return "", "", fmt.Errorf("invalid domain") + } + if ip := net.ParseIP(domain); ip != nil { + return domain, strings.ReplaceAll(domain, ":", "_"), nil + } + if strings.HasPrefix(domain, "*.") && !allowWildcard { + return "", "", fmt.Errorf("wildcard domains are not supported by this operation") + } + if !tlsDNSNamePattern.MatchString(domain) { + return "", "", fmt.Errorf("invalid domain") + } + dirName = strings.ReplaceAll(domain, "*", "_wildcard_") + return domain, dirName, nil +} + +func normalizeTLSStoreName(raw string) (string, error) { + name := strings.TrimSpace(raw) + if !tlsStoreNamePattern.MatchString(name) { + return "", fmt.Errorf("name must use only letters, numbers, dot, underscore, or hyphen") + } + return name, nil +} + +// handleTLSGenerateSelfSigned generates a self-signed TLS certificate for the +// given domain, writes it to /opt/sshpanel/certs//, and returns the paths. +func handleTLSGenerateSelfSigned(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + Domain string `json:"domain"` + } + r.Body = http.MaxBytesReader(w, r.Body, 16*1024) + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Domain == "" { + http.Error(w, "domain required", http.StatusBadRequest) + return + } + domain, dirName, err := normalizeTLSDomain(req.Domain, true) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + certDir := filepath.Join(tlsCertsDir, dirName) + if err := os.MkdirAll(certDir, 0o700); err != nil { + http.Error(w, "mkdir: "+err.Error(), http.StatusInternalServerError) + return + } + certFile := filepath.Join(certDir, "cert.pem") + keyFile := filepath.Join(certDir, "key.pem") + + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + http.Error(w, "keygen: "+err.Error(), http.StatusInternalServerError) + return + } + serialLimit := new(big.Int).Lsh(big.NewInt(1), 128) + serialNumber, err := rand.Int(rand.Reader, serialLimit) + if err != nil { + http.Error(w, "serial generation failed", http.StatusInternalServerError) + return + } + tmpl := &x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{CommonName: domain}, + NotBefore: time.Now().Add(-time.Minute), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{domain}, + } + if net.ParseIP(domain) != nil { + tmpl.DNSNames = nil + tmpl.IPAddresses = []net.IP{net.ParseIP(domain)} + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) + if err != nil { + http.Error(w, "certgen: "+err.Error(), http.StatusInternalServerError) + return + } + privDER, err := x509.MarshalECPrivateKey(priv) + if err != nil { + http.Error(w, "marshal key: "+err.Error(), http.StatusInternalServerError) + return + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privDER}) + if err := writeFileAtomic(certFile, certPEM, 0o600); err != nil { + http.Error(w, "write cert: "+err.Error(), http.StatusInternalServerError) + return + } + if err := writeFileAtomic(keyFile, keyPEM, 0o600); err != nil { + http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "cert_file": certFile, + "key_file": keyFile, + }) +} + +// handleTLSLetsEncrypt runs certbot to obtain a certificate via Let's Encrypt. +// Requires certbot installed on the server and port 80 available. +func handleTLSLetsEncrypt(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + Domain string `json:"domain"` + Email string `json:"email"` + } + r.Body = http.MaxBytesReader(w, r.Body, 16*1024) + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Domain == "" || req.Email == "" { + http.Error(w, "domain and email required", http.StatusBadRequest) + return + } + domain, _, err := normalizeTLSDomain(req.Domain, false) + if err != nil || net.ParseIP(domain) != nil { + http.Error(w, "a valid DNS domain is required", http.StatusBadRequest) + return + } + email := strings.TrimSpace(req.Email) + parsedEmail, err := mail.ParseAddress(email) + if err != nil || parsedEmail.Address != email || len(email) > 254 { + http.Error(w, "valid email required", http.StatusBadRequest) + return + } + + cmd := exec.Command("certbot", "certonly", "--standalone", "--non-interactive", + "--agree-tos", "-m", email, "-d", domain) + out, err := cmd.CombinedOutput() + if err != nil { + http.Error(w, fmt.Sprintf("certbot failed: %v\n%s", err, string(out)), http.StatusInternalServerError) + return + } + + certFile := "/etc/letsencrypt/live/" + domain + "/fullchain.pem" + keyFile := "/etc/letsencrypt/live/" + domain + "/privkey.pem" + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "cert_file": certFile, + "key_file": keyFile, + "output": string(out), + }) +} + +// handleTLSUploadPEM accepts PEM text for cert and key, saves them to disk under +// /opt/sshpanel/certs//, and returns the file paths. +func handleTLSUploadPEM(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + Name string `json:"name"` + Cert string `json:"cert"` + Key string `json:"key"` + } + r.Body = http.MaxBytesReader(w, r.Body, 2<<20) + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" || req.Cert == "" || req.Key == "" { + http.Error(w, "name, cert, and key required", http.StatusBadRequest) + return + } + name, err := normalizeTLSStoreName(req.Name) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if len(req.Cert) > 1024*1024 || len(req.Key) > 1024*1024 { + http.Error(w, "certificate or key is too large", http.StatusRequestEntityTooLarge) + return + } + pair, err := tls.X509KeyPair([]byte(req.Cert), []byte(req.Key)) + if err != nil || len(pair.Certificate) == 0 { + http.Error(w, "certificate and private key are invalid or do not match", http.StatusBadRequest) + return + } + if _, err := x509.ParseCertificate(pair.Certificate[0]); err != nil { + http.Error(w, "invalid leaf certificate", http.StatusBadRequest) + return + } + certDir := filepath.Join(tlsCertsDir, name) + if err := os.MkdirAll(certDir, 0o700); err != nil { + http.Error(w, "mkdir: "+err.Error(), http.StatusInternalServerError) + return + } + certFile := filepath.Join(certDir, "cert.pem") + keyFile := filepath.Join(certDir, "key.pem") + if err := writeFileAtomic(certFile, []byte(req.Cert), 0o600); err != nil { + http.Error(w, "write cert: "+err.Error(), http.StatusInternalServerError) + return + } + if err := writeFileAtomic(keyFile, []byte(req.Key), 0o600); err != nil { + http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "cert_file": certFile, + "key_file": keyFile, + }) +} diff --git a/tls_certs_api.go b/tls_certs_api.go new file mode 100644 index 0000000..4796f7f --- /dev/null +++ b/tls_certs_api.go @@ -0,0 +1,715 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "encoding/json" + "encoding/pem" + "fmt" + "log" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +// Certificate management for the panel: list the TLS material this node already +// uses and replace it in place (fullchain + privkey) when an operator renews a +// certificate. Replacing in place is what makes renewal painless — every place +// that references the old paths (TLS forwarders, Xray inbounds) keeps working, +// and only the listeners that actually serve the certificate are rebound. + +const ( + tlsCertFileName = "cert.pem" + tlsKeyFileName = "key.pem" + // Two PEM blobs plus JSON overhead. Certificates are a few KB; RSA chains + // with several intermediates still stay far below this. + maxTLSCertRequestBody = 4 << 20 + maxTLSPEMBytes = 1 << 20 + // Certificates expiring inside this window are flagged in the panel. + tlsCertExpiryWarnDays = 21 +) + +// tlsCertUsage records one consumer of a certificate so the panel can show what +// a replacement is going to affect. +type tlsCertUsage struct { + Kind string `json:"kind"` // tls_forwarder | xray_inbound + Ref string `json:"ref"` // listen address or inbound tag +} + +type tlsCertInfo struct { + Name string `json:"name"` + CertFile string `json:"cert_file"` + KeyFile string `json:"key_file"` + Managed bool `json:"managed"` // stored under /opt/sshpanel/certs + Exists bool `json:"exists"` + Subject string `json:"subject,omitempty"` + Issuer string `json:"issuer,omitempty"` + Domains []string `json:"domains"` + NotBefore string `json:"not_before,omitempty"` + NotAfter string `json:"not_after,omitempty"` + DaysLeft int `json:"days_left"` + Expired bool `json:"expired"` + Expiring bool `json:"expiring"` + SelfSigned bool `json:"self_signed"` + ChainLen int `json:"chain_length"` + KeyType string `json:"key_type,omitempty"` + KeyOK bool `json:"key_ok"` + Modified string `json:"modified,omitempty"` + Error string `json:"error,omitempty"` + UsedBy []tlsCertUsage `json:"used_by"` +} + +type tlsCertRef struct { + certFile string + keyFile string + managed bool + usage []tlsCertUsage +} + +type tlsCertRefSet struct { + byCert map[string]*tlsCertRef + order []string +} + +func newTLSCertRefSet() *tlsCertRefSet { + return &tlsCertRefSet{byCert: map[string]*tlsCertRef{}} +} + +func (s *tlsCertRefSet) add(certFile, keyFile string, usage ...tlsCertUsage) *tlsCertRef { + certFile = strings.TrimSpace(certFile) + if certFile == "" { + return nil + } + certFile = filepath.Clean(certFile) + ref, ok := s.byCert[certFile] + if !ok { + ref = &tlsCertRef{certFile: certFile, managed: isUnderTLSCertsDir(certFile)} + s.byCert[certFile] = ref + s.order = append(s.order, certFile) + } + if ref.keyFile == "" && strings.TrimSpace(keyFile) != "" { + ref.keyFile = filepath.Clean(strings.TrimSpace(keyFile)) + } + for _, u := range usage { + if u.Kind == "" { + continue + } + dup := false + for _, have := range ref.usage { + if have == u { + dup = true + break + } + } + if !dup { + ref.usage = append(ref.usage, u) + } + } + return ref +} + +func (s *tlsCertRefSet) list() []*tlsCertRef { + out := make([]*tlsCertRef, 0, len(s.order)) + for _, key := range s.order { + out = append(out, s.byCert[key]) + } + return out +} + +func isUnderTLSCertsDir(path string) bool { + rel, err := filepath.Rel(filepath.Clean(tlsCertsDir), filepath.Clean(path)) + if err != nil { + return false + } + return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// samePathRef compares two file paths, following symlinks when both sides can be +// resolved. /etc/letsencrypt/live//fullchain.pem is a symlink, so a +// plain string compare is not enough to match a config reference to a real file. +func samePathRef(a, b string) bool { + a, b = strings.TrimSpace(a), strings.TrimSpace(b) + if a == "" || b == "" { + return false + } + if filepath.Clean(a) == filepath.Clean(b) { + return true + } + ra, errA := filepath.EvalSymlinks(a) + rb, errB := filepath.EvalSymlinks(b) + return errA == nil && errB == nil && ra == rb +} + +// collectTLSCertRefs gathers every certificate this node knows about: the ones +// stored in the panel's cert directory plus the ones referenced by the running +// config (TLS forwarders) and the Xray config (inbound tlsSettings). +func collectTLSCertRefs() *tlsCertRefSet { + set := newTLSCertRefSet() + + gc := getGlobalCfg() + var fallbackCert, fallbackKey string + if gc != nil { + for _, fwd := range gc.TLSForwarders { + if strings.TrimSpace(fwd.CertFile) == "" { + continue + } + if fallbackCert == "" { + fallbackCert, fallbackKey = fwd.CertFile, fwd.KeyFile + } + listen := strings.TrimSpace(fwd.Listen) + if listen == "" { + listen = "(unbound)" + } + set.add(fwd.CertFile, fwd.KeyFile, tlsCertUsage{Kind: "tls_forwarder", Ref: listen}) + } + } + + for _, u := range xrayInboundCertUsage(fallbackCert, fallbackKey) { + set.add(u.certFile, u.keyFile, tlsCertUsage{Kind: "xray_inbound", Ref: u.tag}) + } + + // Panel-managed certificates (self-signed, pasted, or previously updated). + entries, err := os.ReadDir(tlsCertsDir) + if err == nil { + names := make([]string, 0, len(entries)) + for _, e := range entries { + if e.IsDir() { + names = append(names, e.Name()) + } + } + sort.Strings(names) + for _, name := range names { + certFile := filepath.Join(tlsCertsDir, name, tlsCertFileName) + if _, err := os.Stat(certFile); err != nil { + continue + } + set.add(certFile, filepath.Join(tlsCertsDir, name, tlsKeyFileName)) + } + } + return set +} + +type xrayCertRef struct { + tag string + certFile string + keyFile string +} + +// xrayInboundCertUsage returns the certificate each TLS-enabled Xray inbound +// serves. Inbounds that enable TLS without naming a certificate inherit the +// first TLS forwarder's material (see buildInboundTLS), so they are reported +// against that path — replacing it does affect them. +func xrayInboundCertUsage(fallbackCert, fallbackKey string) []xrayCertRef { + if xrayMgr == nil { + return nil + } + data, err := xrayMgr.GetConfig() + if err != nil || len(data) == 0 { + return nil + } + var cf struct { + Inbounds []struct { + Tag string `json:"tag"` + StreamSettings struct { + Security string `json:"security"` + TLSSettings struct { + Certificates []struct { + CertificateFile string `json:"certificateFile"` + KeyFile string `json:"keyFile"` + } `json:"certificates"` + } `json:"tlsSettings"` + } `json:"streamSettings"` + } `json:"inbounds"` + } + if err := json.Unmarshal(data, &cf); err != nil { + return nil + } + var out []xrayCertRef + for i, in := range cf.Inbounds { + security := strings.ToLower(strings.TrimSpace(in.StreamSettings.Security)) + certs := in.StreamSettings.TLSSettings.Certificates + if security != "tls" && len(certs) == 0 { + continue + } + tag := strings.TrimSpace(in.Tag) + if tag == "" { + tag = fmt.Sprintf("inbound-%d", i+1) + } + if len(certs) > 0 && strings.TrimSpace(certs[0].CertificateFile) != "" { + out = append(out, xrayCertRef{tag: tag, certFile: certs[0].CertificateFile, keyFile: certs[0].KeyFile}) + continue + } + if security == "tls" && strings.TrimSpace(fallbackCert) != "" { + out = append(out, xrayCertRef{tag: tag + " (herda do TLS forwarder)", certFile: fallbackCert, keyFile: fallbackKey}) + } + } + return out +} + +func tlsCertDisplayName(certFile string) string { + dir := filepath.Base(filepath.Dir(certFile)) + if dir == "" || dir == "." || dir == string(filepath.Separator) { + return filepath.Base(certFile) + } + if dir == "live" || dir == "certs" { + return filepath.Base(certFile) + } + return dir +} + +func tlsKeyTypeName(key interface{}) string { + switch k := key.(type) { + case *rsa.PrivateKey: + return fmt.Sprintf("RSA %d", k.N.BitLen()) + case *ecdsa.PrivateKey: + return "ECDSA " + k.Curve.Params().Name + case ed25519.PrivateKey: + return "Ed25519" + } + return "" +} + +func parsePEMCertChain(data []byte) ([]*x509.Certificate, error) { + var chain []*x509.Certificate + rest := data + for { + var block *pem.Block + block, rest = pem.Decode(rest) + if block == nil { + break + } + if block.Type != "CERTIFICATE" { + continue + } + crt, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, err + } + chain = append(chain, crt) + } + if len(chain) == 0 { + return nil, fmt.Errorf("no CERTIFICATE block found") + } + return chain, nil +} + +func certDomains(leaf *x509.Certificate) []string { + seen := map[string]bool{} + out := make([]string, 0, len(leaf.DNSNames)+len(leaf.IPAddresses)+1) + for _, d := range leaf.DNSNames { + if d = strings.TrimSpace(d); d != "" && !seen[d] { + seen[d] = true + out = append(out, d) + } + } + for _, ip := range leaf.IPAddresses { + s := ip.String() + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + if len(out) == 0 && strings.TrimSpace(leaf.Subject.CommonName) != "" { + out = append(out, strings.TrimSpace(leaf.Subject.CommonName)) + } + return out +} + +func describeTLSCert(ref *tlsCertRef) tlsCertInfo { + info := tlsCertInfo{ + Name: tlsCertDisplayName(ref.certFile), + CertFile: ref.certFile, + KeyFile: ref.keyFile, + Managed: ref.managed, + Domains: []string{}, + UsedBy: ref.usage, + } + if info.UsedBy == nil { + info.UsedBy = []tlsCertUsage{} + } + st, err := os.Stat(ref.certFile) + if err != nil { + info.Error = "arquivo não encontrado" + return info + } + info.Exists = true + info.Modified = st.ModTime().UTC().Format(time.RFC3339) + + certPEM, err := os.ReadFile(ref.certFile) + if err != nil { + info.Error = "leitura do certificado: " + err.Error() + return info + } + chain, err := parsePEMCertChain(certPEM) + if err != nil { + info.Error = "certificado inválido: " + err.Error() + return info + } + leaf := chain[0] + info.ChainLen = len(chain) + info.Subject = leaf.Subject.CommonName + info.Issuer = leaf.Issuer.CommonName + if info.Issuer == "" && len(leaf.Issuer.Organization) > 0 { + info.Issuer = leaf.Issuer.Organization[0] + } + info.Domains = certDomains(leaf) + info.NotBefore = leaf.NotBefore.UTC().Format(time.RFC3339) + info.NotAfter = leaf.NotAfter.UTC().Format(time.RFC3339) + info.SelfSigned = string(leaf.RawIssuer) == string(leaf.RawSubject) + now := time.Now() + info.Expired = now.After(leaf.NotAfter) + info.DaysLeft = int(leaf.NotAfter.Sub(now).Hours() / 24) + info.Expiring = !info.Expired && info.DaysLeft <= tlsCertExpiryWarnDays + + if ref.keyFile != "" { + keyPEM, err := os.ReadFile(ref.keyFile) + if err != nil { + info.Error = "leitura da chave: " + err.Error() + return info + } + pair, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + info.Error = "a chave privada não corresponde ao certificado" + return info + } + info.KeyOK = true + info.KeyType = tlsKeyTypeName(pair.PrivateKey) + } else { + info.Error = "nenhuma chave privada associada" + } + return info +} + +// handleTLSCertList returns every certificate this node uses, with expiry and +// the listeners/inbounds that serve it. +func handleTLSCertList(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + refs := collectTLSCertRefs().list() + out := make([]tlsCertInfo, 0, len(refs)) + for _, ref := range refs { + out = append(out, describeTLSCert(ref)) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "certs_dir": tlsCertsDir, + "certs": out, + }) +} + +type tlsCertUpdateRequest struct { + // Name creates or replaces a panel-managed certificate under + // /opt/sshpanel/certs//. Ignored when CertFile is set. + Name string `json:"name"` + // CertFile/KeyFile target an existing certificate in place so every + // reference to those paths keeps working after the renewal. + CertFile string `json:"cert_file"` + KeyFile string `json:"key_file"` + // Fullchain/Privkey hold the PEM text. cert/key are accepted as aliases. + Fullchain string `json:"fullchain"` + Privkey string `json:"privkey"` + Cert string `json:"cert"` + Key string `json:"key"` + Reload *bool `json:"reload"` + Force bool `json:"force"` +} + +type tlsCertReloadResult struct { + TLSForwarders []string `json:"tls_forwarders"` + XrayInbounds []string `json:"xray_inbounds"` + XrayRestarted bool `json:"xray_restarted"` +} + +func normalizeTLSFilePath(raw string) (string, error) { + p := strings.TrimSpace(raw) + if p == "" { + return "", fmt.Errorf("caminho vazio") + } + if strings.ContainsAny(p, "\x00\r\n") { + return "", fmt.Errorf("caminho inválido") + } + if !filepath.IsAbs(p) { + return "", fmt.Errorf("o caminho precisa ser absoluto") + } + return filepath.Clean(p), nil +} + +func normalizePEMText(raw string) string { + s := strings.ReplaceAll(strings.TrimSpace(raw), "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + if s == "" { + return "" + } + return s + "\n" +} + +// resolveTLSCertTarget decides which files the new PEM material is written to +// and rejects paths that are neither panel-managed nor already referenced by the +// running configuration. Without that check this endpoint would be an arbitrary +// root file-write primitive. +func resolveTLSCertTarget(req tlsCertUpdateRequest) (certFile, keyFile string, warnings []string, err error) { + if strings.TrimSpace(req.CertFile) != "" { + certFile, err = normalizeTLSFilePath(req.CertFile) + if err != nil { + return "", "", nil, err + } + refs := collectTLSCertRefs() + var known *tlsCertRef + for _, ref := range refs.list() { + if samePathRef(ref.certFile, certFile) { + known = ref + break + } + } + if known == nil && !isUnderTLSCertsDir(certFile) { + return "", "", nil, fmt.Errorf("caminho não gerenciado pelo painel: use um certificado já referenciado na configuração ou informe um nome para armazenar em %s", tlsCertsDir) + } + if strings.TrimSpace(req.KeyFile) != "" { + keyFile, err = normalizeTLSFilePath(req.KeyFile) + if err != nil { + return "", "", nil, err + } + } else if known != nil && known.keyFile != "" { + keyFile = known.keyFile + } else { + keyFile = filepath.Join(filepath.Dir(certFile), tlsKeyFileName) + } + if !isUnderTLSCertsDir(keyFile) { + keyKnown := known != nil && samePathRef(known.keyFile, keyFile) + if !keyKnown && filepath.Dir(keyFile) != filepath.Dir(certFile) { + return "", "", nil, fmt.Errorf("a chave precisa estar na mesma pasta do certificado ou já estar referenciada na configuração") + } + } + return certFile, keyFile, warnings, nil + } + + name, nameErr := normalizeTLSStoreName(req.Name) + if nameErr != nil { + return "", "", nil, fmt.Errorf("informe cert_file de um certificado existente ou um nome para armazenar: %v", nameErr) + } + dir := filepath.Join(tlsCertsDir, name) + return filepath.Join(dir, tlsCertFileName), filepath.Join(dir, tlsKeyFileName), warnings, nil +} + +// writeTLSMaterial replaces path with data, keeping a .bak copy of the previous +// content and preserving the existing file mode. Symlinked targets (certbot +// layout) are followed so the link structure survives the update. +func writeTLSMaterial(path string, data []byte, defaultMode os.FileMode) (string, []string, error) { + var warnings []string + target := path + if lst, err := os.Lstat(path); err == nil && lst.Mode()&os.ModeSymlink != 0 { + if resolved, err := filepath.EvalSymlinks(path); err == nil { + target = resolved + warnings = append(warnings, fmt.Sprintf("%s é um link para %s; o conteúdo real foi substituído", path, resolved)) + } + } + mode := defaultMode + if st, err := os.Stat(target); err == nil { + mode = st.Mode().Perm() + if old, err := os.ReadFile(target); err == nil { + if err := writeFileAtomic(target+".bak", old, mode); err != nil { + warnings = append(warnings, "não foi possível gravar backup de "+filepath.Base(target)+": "+err.Error()) + } + } + } + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + return target, warnings, err + } + if err := writeFileAtomic(target, data, mode); err != nil { + return target, warnings, err + } + return target, warnings, nil +} + +// handleTLSCertUpdate replaces a certificate's fullchain + private key and +// reloads whatever serves it, so a renewal takes effect without touching any +// other configuration. +func handleTLSCertUpdate(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + r.Body = http.MaxBytesReader(w, r.Body, maxTLSCertRequestBody) + var req tlsCertUpdateRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "corpo inválido: "+err.Error(), http.StatusBadRequest) + return + } + if strings.TrimSpace(req.Fullchain) == "" { + req.Fullchain = req.Cert + } + if strings.TrimSpace(req.Privkey) == "" { + req.Privkey = req.Key + } + certPEM := normalizePEMText(req.Fullchain) + keyPEM := normalizePEMText(req.Privkey) + if certPEM == "" || keyPEM == "" { + http.Error(w, "fullchain (certificado) e privkey (chave privada) são obrigatórios", http.StatusBadRequest) + return + } + if len(certPEM) > maxTLSPEMBytes || len(keyPEM) > maxTLSPEMBytes { + http.Error(w, "certificado ou chave muito grandes", http.StatusRequestEntityTooLarge) + return + } + + pair, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM)) + if err != nil || len(pair.Certificate) == 0 { + http.Error(w, "certificado e chave privada inválidos ou não correspondentes", http.StatusBadRequest) + return + } + chain, err := parsePEMCertChain([]byte(certPEM)) + if err != nil { + http.Error(w, "certificado inválido: "+err.Error(), http.StatusBadRequest) + return + } + leaf := chain[0] + now := time.Now() + if now.After(leaf.NotAfter) && !req.Force { + http.Error(w, fmt.Sprintf("este certificado expirou em %s; envie force=true para gravar mesmo assim", + leaf.NotAfter.UTC().Format("2006-01-02")), http.StatusBadRequest) + return + } + + certFile, keyFile, warnings, err := resolveTLSCertTarget(req) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + if len(chain) < 2 && !leaf.IsCA && string(leaf.RawIssuer) != string(leaf.RawSubject) { + warnings = append(warnings, "o PEM enviado contém apenas o certificado final; cole o fullchain.pem completo para evitar erros de cadeia em alguns clientes") + } + if now.Before(leaf.NotBefore) { + warnings = append(warnings, "o certificado só é válido a partir de "+leaf.NotBefore.UTC().Format("2006-01-02 15:04")+" UTC") + } + if now.After(leaf.NotAfter) { + warnings = append(warnings, "certificado já expirado — gravado por causa de force=true") + } + // Domain mismatch is usually a wrong paste, but a domain change can be + // intentional, so it is reported rather than blocked. + if oldPEM, err := os.ReadFile(certFile); err == nil { + if oldChain, err := parsePEMCertChain(oldPEM); err == nil { + oldDomains, newDomains := certDomains(oldChain[0]), certDomains(leaf) + if strings.Join(oldDomains, ",") != strings.Join(newDomains, ",") { + warnings = append(warnings, fmt.Sprintf("os domínios mudaram: antes %s, agora %s", + strings.Join(oldDomains, ", "), strings.Join(newDomains, ", "))) + } + } + } + + writtenCert, certWarn, err := writeTLSMaterial(certFile, []byte(certPEM), 0o600) + warnings = append(warnings, certWarn...) + if err != nil { + http.Error(w, "gravar certificado: "+err.Error(), http.StatusInternalServerError) + return + } + writtenKey, keyWarn, err := writeTLSMaterial(keyFile, []byte(keyPEM), 0o600) + warnings = append(warnings, keyWarn...) + if err != nil { + http.Error(w, "gravar chave: "+err.Error(), http.StatusInternalServerError) + return + } + log.Printf("tls: certificate updated cert=%s key=%s cn=%q not_after=%s", + writtenCert, writtenKey, leaf.Subject.CommonName, leaf.NotAfter.UTC().Format(time.RFC3339)) + + reload := tlsCertReloadResult{TLSForwarders: []string{}, XrayInbounds: []string{}} + if req.Reload == nil || *req.Reload { + var reloadWarn []string + reload, reloadWarn = reloadTLSCertConsumers(certFile, keyFile) + warnings = append(warnings, reloadWarn...) + } + + info := describeTLSCert(&tlsCertRef{ + certFile: certFile, + keyFile: keyFile, + managed: isUnderTLSCertsDir(certFile), + usage: certUsageFor(certFile, keyFile), + }) + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "cert_file": certFile, + "key_file": keyFile, + "cert": info, + "reloaded": reload, + "warnings": warnings, + }) +} + +func certUsageFor(certFile, keyFile string) []tlsCertUsage { + for _, ref := range collectTLSCertRefs().list() { + if samePathRef(ref.certFile, certFile) { + return ref.usage + } + } + return nil +} + +// reloadTLSCertConsumers rebinds the TLS forwarders that serve the replaced +// certificate and restarts Xray when one of its inbounds uses it. Certificates +// are read once when a listener is created, so nothing short of rebinding picks +// up new material. Established connections are not owned by the listeners and +// keep running. +func reloadTLSCertConsumers(certFile, keyFile string) (tlsCertReloadResult, []string) { + result := tlsCertReloadResult{TLSForwarders: []string{}, XrayInbounds: []string{}} + var warnings []string + + gc := getGlobalCfg() + var fallbackCert, fallbackKey string + if gc != nil { + for _, fwd := range gc.TLSForwarders { + if strings.TrimSpace(fwd.CertFile) != "" { + fallbackCert, fallbackKey = fwd.CertFile, fwd.KeyFile + break + } + } + var affected []string + for _, fwd := range gc.TLSForwarders { + if samePathRef(fwd.CertFile, certFile) || samePathRef(fwd.KeyFile, keyFile) { + if listen := strings.TrimSpace(fwd.Listen); listen != "" { + affected = append(affected, listen) + } + } + } + if len(affected) > 0 && tlsPool != nil { + tlsPool.Drop(affected, "certificate updated") + for _, e := range tlsPool.Sync(gc.TLSForwarders) { + warnings = append(warnings, fmt.Sprintf("recarregar TLS forwarder: %v", e)) + } + for _, addr := range affected { + if tlsPool.Has(addr) { + result.TLSForwarders = append(result.TLSForwarders, addr) + } else { + warnings = append(warnings, "o TLS forwarder "+addr+" não voltou a escutar; verifique os logs") + } + } + } + } + + for _, u := range xrayInboundCertUsage(fallbackCert, fallbackKey) { + if samePathRef(u.certFile, certFile) || samePathRef(u.keyFile, keyFile) { + result.XrayInbounds = append(result.XrayInbounds, u.tag) + } + } + if len(result.XrayInbounds) > 0 && xrayMgr != nil { + st := xrayMgr.Status() + if st.Enabled && st.Running { + if err := xrayMgr.Restart(); err != nil { + warnings = append(warnings, fmt.Sprintf("reiniciar Xray: %v", err)) + } else { + result.XrayRestarted = true + } + } else if st.Enabled { + warnings = append(warnings, "o Xray usa este certificado mas não está em execução") + } + } + return result, warnings +} diff --git a/tls_certs_api_test.go b/tls_certs_api_test.go new file mode 100644 index 0000000..0fff02c --- /dev/null +++ b/tls_certs_api_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// makeTestCertPair returns PEM cert/key material for the given domain. +func makeTestCertPair(t *testing.T, domain string, notBefore, notAfter time.Time) (certPEM, keyPEM string) { + t.Helper() + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("keygen: %v", err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + Subject: pkix.Name{CommonName: domain}, + NotBefore: notBefore, + NotAfter: notAfter, + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{domain}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) + if err != nil { + t.Fatalf("certgen: %v", err) + } + keyDER, err := x509.MarshalECPrivateKey(priv) + if err != nil { + t.Fatalf("marshal key: %v", err) + } + certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) + keyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})) + return certPEM, keyPEM +} + +func useTempCertsDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + old := tlsCertsDir + tlsCertsDir = dir + t.Cleanup(func() { tlsCertsDir = old }) + oldCfg := getGlobalCfg() + t.Cleanup(func() { setGlobalCfg(oldCfg) }) + return dir +} + +func postCertUpdate(t *testing.T, body map[string]interface{}) *httptest.ResponseRecorder { + t.Helper() + raw, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/api/tls/certs/update", strings.NewReader(string(raw))) + rec := httptest.NewRecorder() + handleTLSCertUpdate(rec, req) + return rec +} + +func TestCertUpdateStoresNamedCertAndReportsExpiry(t *testing.T) { + dir := useTempCertsDir(t) + certPEM, keyPEM := makeTestCertPair(t, "panel.example.com", time.Now().Add(-time.Hour), time.Now().Add(30*24*time.Hour)) + + rec := postCertUpdate(t, map[string]interface{}{ + "name": "panel-example", + "fullchain": certPEM, + "privkey": keyPEM, + "reload": false, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + CertFile string `json:"cert_file"` + KeyFile string `json:"key_file"` + Cert tlsCertInfo `json:"cert"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + wantCert := filepath.Join(dir, "panel-example", tlsCertFileName) + if filepath.Clean(resp.CertFile) != wantCert { + t.Fatalf("cert_file = %q, want %q", resp.CertFile, wantCert) + } + if !resp.Cert.KeyOK { + t.Fatalf("expected key to match certificate: %+v", resp.Cert) + } + if resp.Cert.Expired || resp.Cert.DaysLeft < 25 { + t.Fatalf("unexpected expiry data: %+v", resp.Cert) + } + if len(resp.Cert.Domains) != 1 || resp.Cert.Domains[0] != "panel.example.com" { + t.Fatalf("domains = %v", resp.Cert.Domains) + } + data, err := os.ReadFile(wantCert) + if err != nil || !strings.Contains(string(data), "BEGIN CERTIFICATE") { + t.Fatalf("cert not written: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "panel-example", tlsKeyFileName)); err != nil { + t.Fatalf("key not written: %v", err) + } +} + +func TestCertUpdateReplacesInPlaceAndKeepsBackup(t *testing.T) { + dir := useTempCertsDir(t) + oldCert, oldKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour)) + if rec := postCertUpdate(t, map[string]interface{}{ + "name": "renew-me", "fullchain": oldCert, "privkey": oldKey, "reload": false, + }); rec.Code != http.StatusOK { + t.Fatalf("seed failed: %s", rec.Body.String()) + } + certFile := filepath.Join(dir, "renew-me", tlsCertFileName) + keyFile := filepath.Join(dir, "renew-me", tlsKeyFileName) + + newCert, newKey := makeTestCertPair(t, "new.example.com", time.Now().Add(-time.Hour), time.Now().Add(90*24*time.Hour)) + rec := postCertUpdate(t, map[string]interface{}{ + "cert_file": certFile, "key_file": keyFile, + "fullchain": newCert, "privkey": newKey, "reload": false, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + Cert tlsCertInfo `json:"cert"` + Warnings []string `json:"warnings"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if resp.Cert.Domains[0] != "new.example.com" { + t.Fatalf("cert was not replaced: %+v", resp.Cert) + } + backup, err := os.ReadFile(certFile + ".bak") + if err != nil { + t.Fatalf("no backup written: %v", err) + } + if strings.TrimSpace(string(backup)) != strings.TrimSpace(oldCert) { + t.Fatal("backup does not hold the previous certificate") + } + if _, err := os.Stat(keyFile + ".bak"); err != nil { + t.Fatalf("no key backup: %v", err) + } + joined := strings.Join(resp.Warnings, " | ") + if !strings.Contains(joined, "domínios mudaram") { + t.Fatalf("expected a domain-change warning, got %q", joined) + } +} + +func TestCertUpdateRejectsBadInput(t *testing.T) { + dir := useTempCertsDir(t) + certPEM, keyPEM := makeTestCertPair(t, "a.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour)) + _, otherKey := makeTestCertPair(t, "b.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour)) + expiredCert, expiredKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-48*time.Hour), time.Now().Add(-time.Hour)) + // Absolute, but neither panel-managed nor referenced by the configuration. + unmanaged := t.TempDir() + + cases := []struct { + name string + body map[string]interface{} + want string + }{ + {"missing key", map[string]interface{}{"name": "x", "fullchain": certPEM}, "obrigatórios"}, + {"mismatched pair", map[string]interface{}{"name": "x", "fullchain": certPEM, "privkey": otherKey}, "não correspondentes"}, + {"expired without force", map[string]interface{}{"name": "x", "fullchain": expiredCert, "privkey": expiredKey}, "expirou"}, + {"unmanaged path", map[string]interface{}{ + "cert_file": filepath.Join(unmanaged, "cert.pem"), + "key_file": filepath.Join(unmanaged, "key.pem"), + "fullchain": certPEM, "privkey": keyPEM, + }, "não gerenciado"}, + {"relative path", map[string]interface{}{"cert_file": "certs/cert.pem", "fullchain": certPEM, "privkey": keyPEM}, "absoluto"}, + {"bad name", map[string]interface{}{"name": "../escape", "fullchain": certPEM, "privkey": keyPEM}, "nome"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := postCertUpdate(t, tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), tc.want) { + t.Fatalf("body %q does not mention %q", rec.Body.String(), tc.want) + } + }) + } + if entries, err := os.ReadDir(dir); err == nil && len(entries) != 0 { + t.Fatalf("rejected requests wrote %d entries to the certs dir", len(entries)) + } +} + +func TestCertUpdateForceAcceptsExpiredCert(t *testing.T) { + useTempCertsDir(t) + expiredCert, expiredKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-48*time.Hour), time.Now().Add(-time.Hour)) + rec := postCertUpdate(t, map[string]interface{}{ + "name": "forced", "fullchain": expiredCert, "privkey": expiredKey, "reload": false, "force": true, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + Cert tlsCertInfo `json:"cert"` + Warnings []string `json:"warnings"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if !resp.Cert.Expired { + t.Fatal("expected the stored certificate to be reported as expired") + } + if !strings.Contains(strings.Join(resp.Warnings, " | "), "expirado") { + t.Fatalf("expected an expiry warning, got %v", resp.Warnings) + } +} + +// A certificate referenced only by the running config (for example a certbot +// path outside the panel directory) must still be updatable in place, because +// that is what makes a renewal invisible to the rest of the configuration. +func TestCertUpdateAllowsPathReferencedByConfig(t *testing.T) { + useTempCertsDir(t) + external := t.TempDir() + certFile := filepath.Join(external, "fullchain.pem") + keyFile := filepath.Join(external, "privkey.pem") + oldCert, oldKey := makeTestCertPair(t, "tunnel.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour)) + if err := os.WriteFile(certFile, []byte(oldCert), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyFile, []byte(oldKey), 0o600); err != nil { + t.Fatal(err) + } + setGlobalCfg(&Config{TLSForwarders: []TLSForwarderConfig{{ + Listen: "0.0.0.0:8443", CertFile: certFile, KeyFile: keyFile, + }}}) + + newCert, newKey := makeTestCertPair(t, "tunnel.example.com", time.Now().Add(-time.Hour), time.Now().Add(60*24*time.Hour)) + rec := postCertUpdate(t, map[string]interface{}{ + "cert_file": certFile, "key_file": keyFile, + "fullchain": newCert, "privkey": newKey, "reload": false, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + stored, err := os.ReadFile(certFile) + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(string(stored)) != strings.TrimSpace(newCert) { + t.Fatal("external certificate path was not updated") + } + var resp struct { + Cert tlsCertInfo `json:"cert"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Cert.UsedBy) != 1 || resp.Cert.UsedBy[0].Ref != "0.0.0.0:8443" { + t.Fatalf("expected the TLS forwarder to be reported as consumer, got %+v", resp.Cert.UsedBy) + } +} + +func TestTLSCertListReportsConfiguredAndManagedCerts(t *testing.T) { + dir := useTempCertsDir(t) + certPEM, keyPEM := makeTestCertPair(t, "listed.example.com", time.Now().Add(-time.Hour), time.Now().Add(10*24*time.Hour)) + if err := os.MkdirAll(filepath.Join(dir, "listed"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "listed", tlsCertFileName), []byte(certPEM), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "listed", tlsKeyFileName), []byte(keyPEM), 0o600); err != nil { + t.Fatal(err) + } + setGlobalCfg(&Config{}) + + req := httptest.NewRequest(http.MethodGet, "/api/tls/certs", nil) + rec := httptest.NewRecorder() + handleTLSCertList(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + Certs []tlsCertInfo `json:"certs"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Certs) != 1 { + t.Fatalf("expected 1 cert, got %d (%+v)", len(resp.Certs), resp.Certs) + } + got := resp.Certs[0] + if got.Name != "listed" || !got.Managed || !got.KeyOK || !got.SelfSigned { + t.Fatalf("unexpected cert info: %+v", got) + } + if !got.Expiring || got.Expired { + t.Fatalf("a cert expiring in 10 days should be flagged as expiring: %+v", got) + } +} diff --git a/tunnel_pipe.go b/tunnel_pipe.go new file mode 100644 index 0000000..6ca1bbe --- /dev/null +++ b/tunnel_pipe.go @@ -0,0 +1,263 @@ +package main + +// This file provides the in-memory connection that carries a tunnelled session +// into this process's own SSH server. +// +// The obvious choice, net.Pipe, is unbuffered: every Write blocks until the +// peer Reads the same bytes. That couples the two sides in lock step, so a +// transport goroutine that is momentarily writing cannot also be draining, and +// each direction pays a scheduler round trip per write. A small buffer in each +// direction removes both problems and matches how a real TCP socket behaves, +// which is what the SSH server on the other end is written against. + +import ( + "errors" + "io" + "net" + "os" + "sync" + "time" +) + +// tunnelPipeBuffer is the per-direction buffer, chosen to hold a full SSH +// handshake plus a couple of maximum-size packets without blocking. It bounds +// memory: two of these per tunnelled session, and nothing grows past them. +const tunnelPipeBuffer = 256 * 1024 + +// tunnelPipe is one direction of the connection: a bounded byte queue with +// deadline-aware blocking reads and writes. +type tunnelPipe struct { + mu sync.Mutex + data []byte + offset int + max int + // signal is closed and replaced whenever the queue changes, so waiters can + // select on it alongside a deadline. This mirrors how the transports in + // this codebase already signal readiness. + signal chan struct{} + closed bool +} + +func newTunnelPipe(max int) *tunnelPipe { + return &tunnelPipe{max: max, signal: make(chan struct{})} +} + +// broadcastLocked wakes every waiter. The caller must hold mu. +func (p *tunnelPipe) broadcastLocked() { + close(p.signal) + p.signal = make(chan struct{}) +} + +func (p *tunnelPipe) availableLocked() int { return len(p.data) - p.offset } + +// compactLocked reclaims the consumed prefix once it is worth the copy. +func (p *tunnelPipe) compactLocked() { + if p.offset == 0 { + return + } + if p.offset == len(p.data) { + p.data = p.data[:0] + p.offset = 0 + return + } + if p.offset >= p.max/2 { + copy(p.data, p.data[p.offset:]) + p.data = p.data[:len(p.data)-p.offset] + p.offset = 0 + } +} + +// write copies data into the queue, blocking while it is full. It returns the +// number of bytes accepted, which is all of them unless the pipe closed or the +// deadline fired. +func (p *tunnelPipe) write(data []byte, deadline func() time.Time) (int, error) { + written := 0 + for len(data) > 0 { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return written, io.ErrClosedPipe + } + p.compactLocked() + room := p.max - p.availableLocked() + if room > 0 { + if room > len(data) { + room = len(data) + } + p.data = append(p.data, data[:room]...) + data = data[room:] + written += room + p.broadcastLocked() + p.mu.Unlock() + continue + } + wait := p.signal + p.mu.Unlock() + if err := waitWithDeadline(wait, deadline); err != nil { + return written, err + } + } + return written, nil +} + +// read copies out whatever is queued, blocking until at least one byte is +// available, the pipe closes, or the deadline fires. +func (p *tunnelPipe) read(out []byte, deadline func() time.Time) (int, error) { + if len(out) == 0 { + return 0, nil + } + for { + p.mu.Lock() + if available := p.availableLocked(); available > 0 { + n := copy(out, p.data[p.offset:]) + p.offset += n + p.compactLocked() + p.broadcastLocked() + p.mu.Unlock() + return n, nil + } + if p.closed { + p.mu.Unlock() + return 0, io.EOF + } + wait := p.signal + p.mu.Unlock() + if err := waitWithDeadline(wait, deadline); err != nil { + return 0, err + } + } +} + +// close marks the direction finished. Queued bytes stay readable so a peer can +// drain what was already sent, matching how a closed TCP socket behaves. +func (p *tunnelPipe) close() { + p.mu.Lock() + if !p.closed { + p.closed = true + p.broadcastLocked() + } + p.mu.Unlock() +} + +// waitWithDeadline blocks until the pipe signals, or the deadline passes. +func waitWithDeadline(signal <-chan struct{}, deadline func() time.Time) error { + at := deadline() + if at.IsZero() { + <-signal + return nil + } + delay := time.Until(at) + if delay <= 0 { + return os.ErrDeadlineExceeded + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-signal: + return nil + case <-timer.C: + return os.ErrDeadlineExceeded + } +} + +// tunnelConn is one end of a buffered in-memory connection. It satisfies +// net.Conn, deadlines included, because the SSH server relies on +// SetReadDeadline to bound an unfinished handshake. +type tunnelConn struct { + recv *tunnelPipe + send *tunnelPipe + addr transportAddr + + deadlineMu sync.RWMutex + readDeadline time.Time + writeDeadline time.Time + + closeOnce sync.Once +} + +// newTunnelConnPair returns the two ends of a buffered connection. Bytes +// written to one end are readable from the other. +func newTunnelConnPair(label string, buffer int) (*tunnelConn, *tunnelConn) { + if buffer <= 0 { + buffer = tunnelPipeBuffer + } + toServer := newTunnelPipe(buffer) + toClient := newTunnelPipe(buffer) + addr := transportAddr(label) + client := &tunnelConn{recv: toClient, send: toServer, addr: addr} + server := &tunnelConn{recv: toServer, send: toClient, addr: addr} + return client, server +} + +func (c *tunnelConn) Read(p []byte) (int, error) { + return c.recv.read(p, c.currentReadDeadline) +} + +func (c *tunnelConn) Write(p []byte) (int, error) { + n, err := c.send.write(p, c.currentWriteDeadline) + if errors.Is(err, io.ErrClosedPipe) && n < len(p) { + return n, io.ErrClosedPipe + } + return n, err +} + +// Close shuts both directions. The peer's pending reads drain what was already +// queued and then see EOF. +func (c *tunnelConn) Close() error { + c.closeOnce.Do(func() { + c.send.close() + c.recv.close() + }) + return nil +} + +func (c *tunnelConn) LocalAddr() net.Addr { return c.addr } +func (c *tunnelConn) RemoteAddr() net.Addr { return c.addr } + +func (c *tunnelConn) SetDeadline(t time.Time) error { + c.deadlineMu.Lock() + c.readDeadline = t + c.writeDeadline = t + c.deadlineMu.Unlock() + c.wakeWaiters() + return nil +} + +func (c *tunnelConn) SetReadDeadline(t time.Time) error { + c.deadlineMu.Lock() + c.readDeadline = t + c.deadlineMu.Unlock() + c.wakeWaiters() + return nil +} + +func (c *tunnelConn) SetWriteDeadline(t time.Time) error { + c.deadlineMu.Lock() + c.writeDeadline = t + c.deadlineMu.Unlock() + c.wakeWaiters() + return nil +} + +// wakeWaiters re-evaluates blocked readers and writers so a deadline set while +// they are parked takes effect instead of being seen only on the next wakeup. +func (c *tunnelConn) wakeWaiters() { + c.recv.mu.Lock() + c.recv.broadcastLocked() + c.recv.mu.Unlock() + c.send.mu.Lock() + c.send.broadcastLocked() + c.send.mu.Unlock() +} + +func (c *tunnelConn) currentReadDeadline() time.Time { + c.deadlineMu.RLock() + defer c.deadlineMu.RUnlock() + return c.readDeadline +} + +func (c *tunnelConn) currentWriteDeadline() time.Time { + c.deadlineMu.RLock() + defer c.deadlineMu.RUnlock() + return c.writeDeadline +} diff --git a/tunnel_share.go b/tunnel_share.go new file mode 100644 index 0000000..8e35ccf --- /dev/null +++ b/tunnel_share.go @@ -0,0 +1,223 @@ +package main + +// This file lets the tunnel transports share the ports the panel already owns: +// the HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080) +// and the TLS forwarders (normally 443). +// +// It works because the protocols on these ports open in mutually incompatible +// ways. A BHTTP frame starts with its mode number (0..5). A BTUN session starts +// with the fixed ASCII marker "DTUNNEL/1.1 CLIENT_HELLO". SSH starts with "SSH-" +// and an HTTP request or status line starts with a method or version letter. +// Each transport's own package owns the check for its wire format, so the rules +// live next to the protocol they describe. +// +// Nothing is ever consumed on a negative verdict: the bytes stay in the +// returned reader, and the caller continues with its normal handling as if this +// file did not exist. + +import ( + "bufio" + "encoding/binary" + "net" + "time" + + "shell2/internal/bhttp" + "shell2/internal/btun" + "shell2/internal/hcr" +) + +// tunnelSniffTimeout bounds how long a shared listener waits for a client's +// first bytes. Every protocol here speaks immediately on connect, so a client +// that says nothing for this long is handed to the normal HTTP/SSH path rather +// than being held any longer. +const tunnelSniffTimeout = 3 * time.Second + +// tunnelSharedReaderSize must hold the largest prefix any sniff can ask for. +const tunnelSharedReaderSize = bhttp.SniffLimit + 64 + +// tunnelShareEnabled reports whether any transport wants the shared ports, so +// the listeners can skip all of this when none do. +func tunnelShareEnabled() bool { + return bhttpShareEnabled() || btunShareEnabled() || hcrShareEnabled() +} + +// tunnelTakeSharedConn inspects the front of a connection that arrived on a +// port owned by another protocol and, when it belongs to a tunnel transport, +// serves it to completion. +// +// It returns the reader to keep using and whether the connection was consumed. +// When it returns false the caller continues with its normal handling, and the +// returned reader holds every byte that was inspected. +func tunnelTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, bool) { + if reader == nil { + reader = bufio.NewReaderSize(conn, tunnelSharedReaderSize) + } + bhttpOn := bhttpShareEnabled() + btunOn := btunShareEnabled() + hcrOn := hcrShareEnabled() + if !bhttpOn && !btunOn && !hcrOn { + return reader, false + } + + // The sniff needs its own deadline: the caller has not set one yet, and a + // client that connects without sending must not wedge this goroutine. + _ = conn.SetReadDeadline(time.Now().Add(tunnelSniffTimeout)) + defer func() { _ = conn.SetReadDeadline(time.Time{}) }() + + // BTUN is checked first because its marker is a fixed string that either + // matches from the first byte or does not. The two transports cannot both + // claim a connection: a BHTTP frame opens with a byte below 6 and the BTUN + // marker opens with 'D'. + if btunOn && tunnelSniff(reader, btunSniffStep) { + return reader, btunServeShared(conn, reader) + } + if hcrOn && tunnelSniff(reader, hcrSniffStep) { + return reader, hcrServeShared(conn, reader) + } + if bhttpOn && tunnelSniff(reader, bhttpSniffStep) { + return reader, bhttpServeShared(conn, reader) + } + return reader, false +} + +// sniffStep inspects the bytes peeked so far. It returns the protocol's verdict +// and, when undecided, how many bytes to peek before asking again. +type sniffStep func(peeked []byte) (verdict int, want int) + +// The verdicts a sniffStep may return, shared by both transports. +const ( + sniffNo = iota + sniffMore + sniffYes +) + +// tunnelSniff runs one protocol's check, peeking progressively so a protocol +// that is rejected on its first byte costs exactly one byte of lookahead. +func tunnelSniff(reader *bufio.Reader, step sniffStep) bool { + want := 1 + for { + peeked, err := reader.Peek(want) + verdict, next := sniffNo, want + if len(peeked) > 0 { + verdict, next = step(peeked) + } + switch { + case verdict == sniffYes: + return true + case verdict == sniffNo: + return false + case err != nil: + // Not enough bytes arrived to decide, so this is not the protocol + // as far as this listener is concerned. + return false + case next <= len(peeked): + // A step that cannot make progress would loop forever. + return false + } + want = next + } +} + +// btunSniffStep matches the fixed BTUN client hello. +func btunSniffStep(peeked []byte) (int, int) { + switch btun.SniffClientHello(peeked) { + case btun.VerdictYes: + return sniffYes, 0 + case btun.VerdictMore: + return sniffMore, btun.SniffLimit + } + return sniffNo, 0 +} + +// bhttpSniffStep matches a BHTTP frame: the header first, then the payload the +// header declares, which is where the magic strings that settle it live. +func bhttpSniffStep(peeked []byte) (int, int) { + switch bhttp.SniffFrame(peeked) { + case bhttp.VerdictYes: + return sniffYes, 0 + case bhttp.VerdictMore: + if len(peeked) < bhttp.HeaderSize { + return sniffMore, bhttp.HeaderSize + } + want := bhttp.HeaderSize + int(binary.BigEndian.Uint32(peeked[25:29])) + if want > bhttp.SniffLimit { + want = bhttp.SniffLimit + } + return sniffMore, want + } + return sniffNo, 0 +} + +// hcrSniffStep matches an HCR request: its opcode, then its fixed version byte, +// then the full 62-byte header. A BHTTP frame whose session byte is not 0x01 is +// rejected at two bytes, so it never waits for 62 bytes. +func hcrSniffStep(peeked []byte) (int, int) { + switch hcr.SniffFrame(peeked) { + case hcr.VerdictYes: + return sniffYes, 0 + case hcr.VerdictMore: + if len(peeked) < 2 { + return sniffMore, 2 + } + return sniffMore, hcr.RequestHeaderSize + } + return sniffNo, 0 +} + +// hcrServeShared hands an identified connection to the running HCR server. +func hcrServeShared(conn net.Conn, reader *bufio.Reader) bool { + hcrMu.Lock() + server := hcrServer + ctx := hcrCtx + hcrMu.Unlock() + if server == nil || ctx == nil { + return false + } + // The engine's own debug log records the session; no extra line here. + server.ServeConn(ctx, &bufferedConn{Conn: conn, r: reader}) + return true +} + +// bhttpServeShared hands an identified connection to the running BHTTP server. +func bhttpServeShared(conn net.Conn, reader *bufio.Reader) bool { + bhttpMu.Lock() + server := bhttpServer + bhttpMu.Unlock() + if server == nil { + return false + } + if bhttpLogConnections() { + bhttpLog.Printf("shared port: %s -> %s handed to BHTTP", conn.RemoteAddr(), conn.LocalAddr()) + } + // The inspected bytes live in the reader, so the server has to read through + // it rather than from the socket. + server.ServeConn(&bufferedConn{Conn: conn, r: reader}) + return true +} + +// btunServeShared hands an identified connection to the running BTUN server. +func btunServeShared(conn net.Conn, reader *bufio.Reader) bool { + btunMu.Lock() + server := btunServer + btunMu.Unlock() + if server == nil { + return false + } + if btunLogConnections() { + btunLog.Printf("shared port: %s -> %s handed to BTUN", conn.RemoteAddr(), conn.LocalAddr()) + } + server.ServeConn(&bufferedConn{Conn: conn, r: reader}) + return true +} + +func bhttpLogConnections() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.BHTTP != nil && globalCfg.BHTTP.LogConnections +} + +func btunLogConnections() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.BTUN != nil && globalCfg.BTUN.LogConnections +} diff --git a/udpgw_integration.go b/udpgw_integration.go new file mode 100644 index 0000000..5cf557f --- /dev/null +++ b/udpgw_integration.go @@ -0,0 +1,685 @@ +package main + +// This file embeds the UDP gateway (udpgw) service into the main +// application. The original udpgw program (public domain) accepts a +// TCP connection, then forwards framed UDP datagrams to arbitrary +// destinations and demultiplexes replies back to the originating +// connection. Here we expose the same functionality via a +// configuration key in config.json. When enabled, the server binds +// to the provided Listen address (or the default 0.0.0.0:7400 if +// unspecified) and handles each client in its own goroutine. The +// gateway runs entirely in‑process and behaves like the standalone +// badvpn-udpgw daemon. + +import ( + "bufio" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "strings" + "sync" + "time" +) + +// Safe ceilings applied regardless of config, so oversized values left in an +// existing config.json cannot bloat per-client memory at scale. +const ( + udpgwSocketBufferMax = 512 * 1024 // per-client UDP socket buffer (kernel memory) + udpgwWriteChanMax = 1024 // per-client reply queue slots + udpgwDefaultMaxClients = 10000 // total concurrent client cap +) + +var ( + udpgwMu sync.Mutex + udpgwLn net.Listener + udpgwClients = make(map[net.Conn]struct{}) + // udpgwClientLimit is the max concurrent clients (0 = unlimited). Set when + // the listener starts and read on every accept, all under udpgwMu. + udpgwClientLimit int + // udpgwClientsRejected counts clients turned away at the cap, for logging + // and future stats. Guarded by udpgwMu. + udpgwClientsRejected int64 + + udpgwAutoMu sync.Mutex + udpgwAutoCancel context.CancelFunc +) + +// stopUDPGW closes the active UDPGW listener, all active UDPGW client TCP +// sockets, and the optional auto-restart watchdog. It is a no-op if UDPGW is +// not running. +func stopUDPGW() { + stopUDPGWAutoRestart() + stopUDPGWInstance() +} + +func stopUDPGWInstance() { + udpgwMu.Lock() + defer udpgwMu.Unlock() + if udpgwLn != nil { + _ = udpgwLn.Close() + udpgwLn = nil + } + for conn := range udpgwClients { + _ = conn.Close() + delete(udpgwClients, conn) + } +} + +func stopUDPGWAutoRestart() { + udpgwAutoMu.Lock() + defer udpgwAutoMu.Unlock() + if udpgwAutoCancel != nil { + udpgwAutoCancel() + udpgwAutoCancel = nil + } +} + +func registerUDPGWClient(conn net.Conn) bool { + udpgwMu.Lock() + defer udpgwMu.Unlock() + if udpgwLn == nil { + _ = conn.Close() + return false + } + // Reject past the hard client cap so a surge cannot exhaust memory. + if udpgwClientLimit > 0 && len(udpgwClients) >= udpgwClientLimit { + udpgwClientsRejected++ + rejected := udpgwClientsRejected + _ = conn.Close() + // Log the first rejection and then every 1000th to avoid log spam. + if rejected == 1 || rejected%1000 == 0 { + log.Printf("udpgw: client cap reached (%d); rejected %d client(s) so far", udpgwClientLimit, rejected) + } + return false + } + udpgwClients[conn] = struct{}{} + return true +} + +func unregisterUDPGWClient(conn net.Conn) { + udpgwMu.Lock() + delete(udpgwClients, conn) + udpgwMu.Unlock() +} + +func udpgwRunning() bool { + udpgwMu.Lock() + defer udpgwMu.Unlock() + return udpgwLn != nil +} + +// startUDPGW starts the integrated UDP gateway if cfg is non‑nil and +// cfg.Listen is non‑empty. It applies default values to any zero +// configuration fields and converts duration strings to time.Duration. +// The server runs in a goroutine; any fatal errors are logged and +// prevent the gateway from starting, but do not terminate the main +// process. +func startUDPGW(cfg *UDPGWConfig) error { + if cfg == nil { + return nil + } + stopUDPGWAutoRestart() + if err := startUDPGWInstance(cfg); err != nil { + return err + } + startUDPGWAutoRestart(cfg) + return nil +} + +func startUDPGWInstance(cfg *UDPGWConfig) error { + if cfg == nil { + return nil + } + // Default the listen address to the standalone default (0.0.0.0:7400) if + // unspecified. This matches the behaviour of the original + // badvpn-udpgw program, which listens on all interfaces by default. + listenAddr := cfg.Listen + if listenAddr == "" { + listenAddr = defaultUDPGWListen + } + cfg.Listen = listenAddr + // Apply defaults for numeric fields if zero. + c := &internalUDPGWConfig{} + c.listen = listenAddr + if cfg.MaxFrame > 0 { + c.maxFrame = cfg.MaxFrame + } else { + c.maxFrame = 64 * 1024 + } + c.debug = cfg.Debug + if cfg.HexdumpN > 0 { + c.hexdumpN = cfg.HexdumpN + } else { + c.hexdumpN = 64 + } + // Per-client outgoing frame queue. A large queue costs ~24 B/slot of heap + // per client even when empty; at thousands of clients that adds up. UDP is + // lossy by nature, so a smaller queue that drops under backpressure is fine. + // The value is clamped to udpgwWriteChanMax so an oversized value left in an + // old config.json is ignored; only smaller custom values are honored. + c.writeChan = udpgwWriteChanMax + if cfg.WriteChan > 0 && cfg.WriteChan < udpgwWriteChanMax { + c.writeChan = cfg.WriteChan + } + c.udpBindIP = cfg.UDPBindIP + // Per-client UDP socket buffers are KERNEL memory, allocated per connected + // client. 8 MB per socket is fine for a single process-wide listener, but + // here every tunnel user gets its own socket, so a large value multiplied by + // thousands of clients can exhaust kernel memory (especially if + // net.core.rmem_max was raised for DNSTT). Clamp to udpgwSocketBufferMax so + // old large config values are ignored; only smaller custom values are used. + c.udpRBuf = udpgwSocketBufferMax + if cfg.UDPRBuf > 0 && cfg.UDPRBuf < udpgwSocketBufferMax { + c.udpRBuf = cfg.UDPRBuf + } + c.udpWBuf = udpgwSocketBufferMax + if cfg.UDPWBuf > 0 && cfg.UDPWBuf < udpgwSocketBufferMax { + c.udpWBuf = cfg.UDPWBuf + } + // Parse durations with fallback defaults. + if cfg.MapTTL != "" { + if d, err := time.ParseDuration(cfg.MapTTL); err == nil { + c.mapTTL = d + } else { + log.Printf("udpgw: invalid map_ttl %q: %v; using default 90s", cfg.MapTTL, err) + c.mapTTL = 90 * time.Second + } + } else { + c.mapTTL = 90 * time.Second + } + if cfg.ReapEvery != "" { + if d, err := time.ParseDuration(cfg.ReapEvery); err == nil { + c.reapEvery = d + } else { + log.Printf("udpgw: invalid reap_every %q: %v; using default 10s", cfg.ReapEvery, err) + c.reapEvery = 10 * time.Second + } + } else { + c.reapEvery = 10 * time.Second + } + // Idle timeout for TCP clients. + if cfg.IdleTimeout != "" { + if d, err := time.ParseDuration(cfg.IdleTimeout); err == nil { + c.idleTimeout = d + } else { + log.Printf("udpgw: invalid idle_timeout %q: %v; using default 2m", cfg.IdleTimeout, err) + c.idleTimeout = 2 * time.Minute + } + } else { + c.idleTimeout = 2 * time.Minute + } + // Per-client logical connID cap. + if cfg.MaxClientConns > 0 { + c.maxClientConns = cfg.MaxClientConns + } else { + c.maxClientConns = 10 + } + // Per-client destination mapping cap. + if cfg.MaxMapEntries > 0 { + c.maxMapEntries = cfg.MaxMapEntries + } else { + c.maxMapEntries = 32768 + } + // Total concurrent client cap. New clients past this are rejected so a + // surge (e.g. well past normal load) cannot exhaust memory and crash. + if cfg.MaxClients > 0 { + c.maxClients = cfg.MaxClients + } else { + c.maxClients = udpgwDefaultMaxClients + } + // Start listening. + ln, err := net.Listen("tcp", c.listen) + if err != nil { + log.Printf("udpgw: listen failed on %s: %v", c.listen, err) + return fmt.Errorf("udpgw: listen failed on %s: %w", c.listen, err) + } + + // Register as the active listener so stopUDPGW can close it, and publish + // the current client cap so registerUDPGWClient can enforce it. + udpgwMu.Lock() + if udpgwLn != nil { + _ = udpgwLn.Close() + } + udpgwLn = ln + udpgwClientLimit = c.maxClients + udpgwMu.Unlock() + + if c.debug { + log.Printf("udpgw: listening on %s", c.listen) + } + go func() { + for { + conn, err := ln.Accept() + if err != nil { + if errors.Is(err, net.ErrClosed) { + return + } + log.Printf("udpgw: accept error: %v", err) + continue + } + if !registerUDPGWClient(conn) { + continue + } + go func(client net.Conn) { + defer unregisterUDPGWClient(client) + handleUDPGWClient(client, c) + }(conn) + } + }() + return nil +} + +func startUDPGWAutoRestart(cfg *UDPGWConfig) { + interval := udpgwAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := udpgwAutoRestartGrace(cfg) + cfgCopy := *cfg + ctx, cancel := context.WithCancel(context.Background()) + + udpgwAutoMu.Lock() + if udpgwAutoCancel != nil { + udpgwAutoCancel() + } + udpgwAutoCancel = cancel + udpgwAutoMu.Unlock() + + go func() { + t := time.NewTicker(interval) + defer t.Stop() + log.Printf("udpgw: auto restart enabled: interval=%s grace=%s mode=hard", interval, grace) + for { + select { + case <-ctx.Done(): + return + case <-t.C: + log.Printf("udpgw: auto restart: stopping listener and connected clients") + stopUDPGWInstance() + if !sleepOrContextDone(ctx, grace) { + return + } + for attempt := 1; ; attempt++ { + if err := startUDPGWInstance(&cfgCopy); err != nil { + log.Printf("udpgw: auto restart: start attempt %d failed: %v", attempt, err) + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + continue + } + log.Printf("udpgw: auto restart: listener and client handler restarted") + break + } + } + } + }() +} + +func udpgwAutoRestartInterval(cfg *UDPGWConfig) time.Duration { + if cfg == nil { + return 0 + } + raw := strings.TrimSpace(cfg.AutoRestartInterval) + if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + log.Printf("udpgw: auto restart disabled: invalid interval %q: %v", raw, err) + return 0 + } + if d < time.Minute { + log.Printf("udpgw: auto restart disabled: interval %q is below minimum 1m", raw) + return 0 + } + return d +} + +func udpgwAutoRestartGrace(cfg *UDPGWConfig) time.Duration { + if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" { + return 2 * time.Second + } + d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace)) + if err != nil || d < 0 { + log.Printf("udpgw: auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace) + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +// internalUDPGWConfig mirrors the exported UDPGWConfig but with +// time.Duration fields for TTL and reaper intervals. It does not +// embed JSON tags because it is not exposed to the user. +type internalUDPGWConfig struct { + listen string + maxFrame int + debug bool + hexdumpN int + writeChan int + udpBindIP string + udpRBuf int + udpWBuf int + mapTTL time.Duration + reapEvery time.Duration + idleTimeout time.Duration + maxClientConns int + maxMapEntries int + maxClients int +} + +// udpDestKey identifies a destination IPv4:port for the UDP gateway. A +// mapping of this key to a connID+x byte is kept per client so +// replies can be routed correctly. Each client maintains its own map +// of udpDestKey->udpMapVal entries. +type udpDestKey struct { + ip [4]byte + port uint16 +} + +// udpMapVal stores the mapping from udpDestKey to connID, the x byte and the +// expiration time. +type udpMapVal struct { + connID uint16 + x byte + exp time.Time +} + +// handleUDPGWClient manages a single TCP client connection to the UDP +// gateway. It creates a per‑client UDP socket, reads frames from the +// TCP connection, sends UDP datagrams to the requested destination, +// maintains a mapping of udpDestKey->udpMapVal for routing replies, and +// writes reply frames back over the TCP connection. When the client +// disconnects or an error occurs, all goroutines are terminated and the +// UDP socket is closed. +func handleUDPGWClient(conn net.Conn, c *internalUDPGWConfig) { + defer conn.Close() + remote := conn.RemoteAddr().String() + if c.debug { + log.Printf("udpgw: client connected: %s", remote) + } + // Lower latency for interactive applications by disabling Nagle. + if tcp, ok := conn.(*net.TCPConn); ok { + _ = tcp.SetNoDelay(true) + } + // 32 KiB is ample for reading length-prefixed UDPGW frames (which are + // MTU-sized in practice). bufio serves reads larger than its buffer by + // reading straight into the caller's slice, so max-frame reads still work. + // The old 256 KiB buffer wasted ~224 KiB of heap per connected client. + br := bufio.NewReaderSize(conn, 32*1024) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // Bind a UDP socket for this client. Use cfg.udpBindIP if provided. + var laddr *net.UDPAddr + if c.udpBindIP != "" { + ip := net.ParseIP(c.udpBindIP) + if ip != nil { + laddr = &net.UDPAddr{IP: ip, Port: 0} + } else { + log.Printf("udpgw[%s]: invalid udp_bind IP %q", remote, c.udpBindIP) + return + } + } + udpConn, err := net.ListenUDP("udp", laddr) + if err != nil { + log.Printf("udpgw[%s]: UDP listen failed: %v", remote, err) + return + } + defer udpConn.Close() + _ = udpConn.SetReadBuffer(c.udpRBuf) + _ = udpConn.SetWriteBuffer(c.udpWBuf) + // Channel to queue outgoing frames back to the client. + writeCh := make(chan []byte, c.writeChan) + done := make(chan struct{}) + go func() { + defer close(done) + for { + select { + case <-ctx.Done(): + return + case b := <-writeCh: + if len(b) == 0 { + continue + } + // If the client stops reading, don't block forever. + _ = conn.SetWriteDeadline(time.Now().Add(30 * time.Second)) + _, err := conn.Write(b) + if err != nil { + cancel() + return + } + } + } + }() + // Destination -> connID+x mapping and active connID tracking per TCP client. + var mu sync.Mutex + destToConn := make(map[udpDestKey]udpMapVal) + connIDLastSeen := make(map[uint16]time.Time) + // Start a reaper goroutine to purge expired mappings. + // Uses ctx instead of a separate stopReaper channel so that cancellation + // is always uniform: any exit path that calls cancel() (error, disconnect, + // idle timeout, panic-deferred cancel) also stops the reaper. + go func() { + t := time.NewTicker(c.reapEvery) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + now := time.Now() + mu.Lock() + for k, v := range destToConn { + if now.After(v.exp) { + delete(destToConn, k) + } + } + for id, lastSeen := range connIDLastSeen { + if now.Sub(lastSeen) > c.mapTTL { + delete(connIDLastSeen, id) + } + } + mu.Unlock() + } + } + }() + // Goroutine to read UDP replies and write framed responses back. + go func() { + buf := make([]byte, 65535) + for { + n, from, err := udpConn.ReadFromUDP(buf) + if err != nil { + return + } + if n <= 0 { + continue + } + ip4 := from.IP.To4() + if ip4 == nil { + // IPv6 replies are dropped because framing only supports IPv4. + continue + } + k := udpDestKey{port: uint16(from.Port)} + copy(k.ip[:], ip4) + mu.Lock() + v, ok := destToConn[k] + mu.Unlock() + if !ok || time.Now().After(v.exp) { + if c.debug { + log.Printf("udpgw[%s]: dropping %dB from %s (no mapping)", remote, n, from.String()) + } + continue + } + // Avoid unbounded memory growth: if the client is slow and the + // write queue is full, drop replies rather than allocating more. + if len(writeCh) == cap(writeCh) { + if c.debug { + log.Printf("udpgw[%s]: drop UDP reply %dB from %s (write queue full)", remote, n, from.String()) + } + continue + } + frame := udpgwBuildFrame(v.connID, v.x, k.ip, k.port, buf[:n]) + select { + case <-ctx.Done(): + return + case writeCh <- frame: + default: + // Race with another sender filling the channel. + } + if c.debug { + log.Printf("udpgw[%s]: UDP<- %dB from %s -> connID=%d x=0x%02x", remote, n, from.String(), v.connID, v.x) + } + } + }() + // Main loop: read frames from TCP, update mapping and send UDP. + for { + // Close idle TCP clients to avoid leaking goroutines. + if c.idleTimeout > 0 { + _ = conn.SetReadDeadline(time.Now().Add(c.idleTimeout)) + } + payload, err := udpgwReadPayload(br, c.maxFrame) + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Timeout() { + if c.debug { + log.Printf("udpgw[%s]: idle timeout (%s); closing", remote, c.idleTimeout) + } + } + if err == io.EOF { + if c.debug { + log.Printf("udpgw: client disconnected: %s", remote) + } + } else { + log.Printf("udpgw[%s]: read error: %v", remote, err) + } + cancel() + _ = conn.Close() + <-done + return + } + // payload: connID(2) + X(1) + dstIPv4(4) + dstPort(2) + data + if len(payload) < 2+1+4+2 { + if c.debug { + log.Printf("udpgw[%s]: too short payload %dB", remote, len(payload)) + } + continue + } + connID := binary.BigEndian.Uint16(payload[0:2]) + x := payload[2] + var dstIP [4]byte + copy(dstIP[:], payload[3:7]) + dstPort := binary.BigEndian.Uint16(payload[7:9]) + data := payload[9:] + if c.debug { + log.Printf("udpgw[%s]: RX connID=%d dst=%d.%d.%d.%d:%d x=0x%02x len=%d", remote, connID, dstIP[0], dstIP[1], dstIP[2], dstIP[3], dstPort, x, len(data)) + } + // Enforce a per-client logical session cap using udpgw connID. + k := udpDestKey{ip: dstIP, port: dstPort} + now := time.Now() + mu.Lock() + // Step 1: evict TTL-expired connIDs first. + for id, lastSeen := range connIDLastSeen { + if now.Sub(lastSeen) > c.mapTTL { + delete(connIDLastSeen, id) + } + } + // Step 2: if the connID is new and we are still at or above the cap + // after TTL eviction, evict the single oldest entry to make room. + // This prevents a client rotating connIDs faster than mapTTL from + // bypassing maxClientConns and growing the map indefinitely. + if _, alreadyKnown := connIDLastSeen[connID]; !alreadyKnown && c.maxClientConns > 0 && len(connIDLastSeen) >= c.maxClientConns { + // Find and remove the oldest connID seen. + var oldestID uint16 + var oldestTime time.Time + first := true + for id, lastSeen := range connIDLastSeen { + if first || lastSeen.Before(oldestTime) { + oldestID = id + oldestTime = lastSeen + first = false + } + } + delete(connIDLastSeen, oldestID) + if c.debug { + log.Printf("udpgw[%s]: connID cap reached (%d); evicted oldest connID=%d to admit connID=%d", remote, c.maxClientConns, oldestID, connID) + } + } + connIDLastSeen[connID] = now + // Update the mapping (bounded to protect memory). + if c.maxMapEntries > 0 && len(destToConn) >= c.maxMapEntries { + // First, purge expired entries. + for dk, dv := range destToConn { + if now.After(dv.exp) { + delete(destToConn, dk) + } + } + // If still too large, evict arbitrary entries until we're under the cap. + if len(destToConn) >= c.maxMapEntries { + evict := (len(destToConn) - c.maxMapEntries) + 1 + for dk := range destToConn { + delete(destToConn, dk) + evict-- + if evict <= 0 { + break + } + } + if c.debug { + log.Printf("udpgw[%s]: mapping cap reached; evicted entries, size=%d", remote, len(destToConn)) + } + } + } + destToConn[k] = udpMapVal{connID: connID, x: x, exp: now.Add(c.mapTTL)} + mu.Unlock() + // Send the UDP datagram. + raddr := &net.UDPAddr{IP: net.IP(dstIP[:]), Port: int(dstPort)} + _, err = udpConn.WriteToUDP(data, raddr) + if err != nil { + if c.debug { + log.Printf("udpgw[%s]: UDP write failed to %s: %v", remote, raddr.String(), err) + } + continue + } + if c.debug { + log.Printf("udpgw[%s]: UDP-> %dB to %s", remote, len(data), raddr.String()) + } + } +} + +// udpgwReadPayload reads a length‑prefixed payload from r. The length +// prefix is a little‑endian uint16. Payloads larger than max cause an +// error. +func udpgwReadPayload(r *bufio.Reader, max int) ([]byte, error) { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, err + } + n := int(binary.LittleEndian.Uint16(lenBuf[:])) + if n <= 0 || n > max { + return nil, fmt.Errorf("udpgw: invalid frame length %d", n) + } + b := make([]byte, n) + if _, err := io.ReadFull(r, b); err != nil { + return nil, err + } + return b, nil +} + +// udpgwBuildFrame constructs a reply frame for the client. The frame +// consists of a little‑endian length prefix, then connID (big endian), +// x byte, source IPv4, source port, and the data. +func udpgwBuildFrame(connID uint16, x byte, ip [4]byte, port uint16, data []byte) []byte { + payloadLen := 2 + 1 + 4 + 2 + len(data) + out := make([]byte, 2+payloadLen) + binary.LittleEndian.PutUint16(out[0:2], uint16(payloadLen)) + binary.BigEndian.PutUint16(out[2:4], connID) + out[4] = x + copy(out[5:9], ip[:]) + binary.BigEndian.PutUint16(out[9:11], port) + copy(out[11:], data) + return out +} diff --git a/update.sh b/update.sh new file mode 100644 index 0000000..d72aae4 --- /dev/null +++ b/update.sh @@ -0,0 +1,614 @@ +#!/bin/bash +# Update the DragonCoreSSH CLI from a local extracted release. +# +# Preserved: +# - /opt/sshpanel/.env +# - /opt/sshpanel/config.json +# - /opt/sshpanel/xray_config.json +# - SSH keys, certs, logs, database, users +# +# Usage: +# sudo bash /opt/sshpanel/update.sh +# sudo bash update.sh +# +# Run from an extracted DragonCoreSSH-CLI source directory to apply that release. +# Installed /opt/sshpanel/update.sh rebuilds the cached CLI source. +set -euo pipefail + +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m' +info() { echo -e "${GREEN}[+]${NC} $*"; } +warn() { echo -e "${YELLOW}[!]${NC} $*"; } +error() { echo -e "${RED}[x]${NC} $*"; exit 1; } + +# Config +INSTALL_DIR="${INSTALL_DIR:-/opt/sshpanel}" +SERVICE_NAME="${SERVICE_NAME:-sshpanel}" +LOG_TMPFS_SIZE="${LOG_TMPFS_SIZE:-15m}" +PANEL_LOG_MAX_BYTES="${PANEL_LOG_MAX_BYTES:-1048576}" +REPO_URL="local-cli-source" +UPDATE_REF="${UPDATE_REF:-}" +SOURCE_CACHE_DIR="${SOURCE_CACHE_DIR:-${INSTALL_DIR}/source}" +MKDIR_BIN="$(command -v mkdir 2>/dev/null || true)" +[[ -n "$MKDIR_BIN" ]] || MKDIR_BIN="/bin/mkdir" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SOURCE_DIR="" +RESTART_NEEDED=false +BUILD_COMMIT="" +BUILD_BRANCH="" +BUILD_TIME="" +BUILD_REPO_URL="" + +[[ $EUID -ne 0 ]] && error "Run as root: sudo bash $0" + +# Cross-distro helpers ------------------------------------------------------- +PKG_MANAGER="" +UPDATE_DEPS=() +SYSTEMCTL_BIN="" +SH_BIN="$(command -v sh 2>/dev/null || echo /bin/sh)" +MOUNT_BIN="$(command -v mount 2>/dev/null || echo /bin/mount)" +MOUNTPOINT_BIN="$(command -v mountpoint 2>/dev/null || echo /usr/bin/mountpoint)" +TOUCH_BIN="$(command -v touch 2>/dev/null || echo /usr/bin/touch)" +CHMOD_BIN="$(command -v chmod 2>/dev/null || echo /usr/bin/chmod)" + +require_systemd() { + SYSTEMCTL_BIN="$(command -v systemctl 2>/dev/null || true)" + if [[ -z "$SYSTEMCTL_BIN" ]]; then + error "systemd was not found. This updater supports Linux distributions that use systemd for services." + fi +} + +detect_pkg_manager() { + if command -v apt-get >/dev/null 2>&1; then + PKG_MANAGER="apt" + elif command -v dnf >/dev/null 2>&1; then + PKG_MANAGER="dnf" + elif command -v yum >/dev/null 2>&1; then + PKG_MANAGER="yum" + elif command -v zypper >/dev/null 2>&1; then + PKG_MANAGER="zypper" + elif command -v pacman >/dev/null 2>&1; then + PKG_MANAGER="pacman" + elif command -v apk >/dev/null 2>&1; then + PKG_MANAGER="apk" + else + error "No supported package manager found. Supported: apt, dnf, yum, zypper, pacman, apk." + fi +} + +set_update_deps() { + case "$PKG_MANAGER" in + apt) + UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip) + ;; + dnf|yum) + UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip) + ;; + zypper) + UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip) + ;; + pacman) + UPDATE_DEPS=(git rsync wget ca-certificates python gcc make tar gzip) + ;; + apk) + UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip) + ;; + esac +} + +pkg_update() { + case "$PKG_MANAGER" in + apt) apt-get update -qq ;; + dnf) dnf makecache -q ;; + yum) yum makecache -q ;; + zypper) zypper --non-interactive refresh ;; + pacman) pacman -Sy --noconfirm ;; + apk) apk update ;; + esac +} + +pkg_install() { + case "$PKG_MANAGER" in + apt) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@" ;; + dnf) dnf install -y "$@" ;; + yum) yum install -y "$@" ;; + zypper) zypper --non-interactive install -y "$@" ;; + pacman) pacman -S --noconfirm --needed "$@" ;; + apk) apk add --no-cache "$@" ;; + esac +} + +ensure_update_dependencies() { + local missing=false cmd + for cmd in git rsync wget tar gzip gcc make; do + if ! command -v "$cmd" >/dev/null 2>&1; then + missing=true + fi + done + if ! command -v python3 >/dev/null 2>&1; then + missing=true + fi + if $missing; then + warn "One or more updater dependencies are missing. Installing them with $PKG_MANAGER..." + pkg_update + pkg_install "${UPDATE_DEPS[@]}" + fi + if ! command -v python3 >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then + ln -sf "$(command -v python)" /usr/local/bin/python3 2>/dev/null || true + fi +} + +echo -e "\n${GREEN}==========================================${NC}" +echo -e "${GREEN} DragonCoreSSH / SSH Panel Updater ${NC}" +echo -e "${GREEN}==========================================${NC}\n" + +# Helpers +need_cmd() { + command -v "$1" >/dev/null 2>&1 || error "Required command not found: $1" +} + +ensure_log_tmpfs_mount() { + local log_dir="${INSTALL_DIR}/logs" + local opts="rw,nosuid,nodev,noexec,noatime,nofail,size=${LOG_TMPFS_SIZE},mode=0755" + local tmp_fstab + + mkdir -p "$log_dir" + + if [[ -f /etc/fstab ]]; then + cp /etc/fstab "/etc/fstab.sshpanel.bak.$(date +%s)" 2>/dev/null || true + tmp_fstab="$(mktemp)" + awk -v mp="$log_dir" '!(($1 == "tmpfs") && ($2 == mp) && ($3 == "tmpfs")) {print}' /etc/fstab > "$tmp_fstab" + printf 'tmpfs %s tmpfs %s 0 0\n' "$log_dir" "$opts" >> "$tmp_fstab" + cat "$tmp_fstab" > /etc/fstab + rm -f "$tmp_fstab" + info " Log RAM disk automount saved in /etc/fstab: $log_dir (${LOG_TMPFS_SIZE})" + else + warn " /etc/fstab not found; service startup fallback will mount $log_dir as tmpfs" + fi + + "${SYSTEMCTL_BIN:-systemctl}" daemon-reload >/dev/null 2>&1 || true + if command -v mountpoint >/dev/null 2>&1 && mountpoint -q "$log_dir"; then + mount -o "remount,size=${LOG_TMPFS_SIZE},mode=0755" "$log_dir" >/dev/null 2>&1 || true + else + mount "$log_dir" >/dev/null 2>&1 || mount -t tmpfs -o "size=${LOG_TMPFS_SIZE},mode=0755" tmpfs "$log_dir" >/dev/null 2>&1 || \ + warn " Could not mount $log_dir as tmpfs now; service startup fallback will try again" + fi + + touch "$log_dir/panel.log" >/dev/null 2>&1 || true + chmod 0644 "$log_dir/panel.log" >/dev/null 2>&1 || true +} + +install_git_if_missing() { + if command -v git >/dev/null 2>&1; then + return 0 + fi + warn "git is not installed. Trying to install it..." + pkg_update + pkg_install git ca-certificates +} + +remote_default_branch() { + local branch + branch="$(git ls-remote --symref "$REPO_URL" HEAD 2>/dev/null | awk '/^ref:/ {sub("refs/heads/", "", $2); print $2; exit}')" + if [[ -n "$branch" ]]; then + printf '%s\n' "$branch" + else + printf 'main\n' + fi +} + +prepare_source_from_git() { + SOURCE_DIR="${SOURCE_DIR:-$SCRIPT_DIR}" + if [[ ! -f "$SOURCE_DIR/go.mod" ]]; then + SOURCE_DIR="$SOURCE_CACHE_DIR" + fi + info "[1/7] Using local CLI source: $SOURCE_DIR" + [[ -f "$SOURCE_DIR/go.mod" ]] || error "go.mod not found; run update.sh from an extracted CLI release" + [[ -f "$SOURCE_DIR/dragoncore_cli.py" ]] || error "Source is missing dragoncore_cli.py" +} + +install_go_if_needed() { + local go_version machine goarch go_url current_go need_go + go_version="$(awk '$1 == "go" {print $2; exit}' "$SOURCE_DIR/go.mod" 2>/dev/null || echo "1.22.5")" + need_go=true + + info "[2/7] Checking Go toolchain..." + info " Required Go: $go_version" + + if command -v go >/dev/null 2>&1; then + current_go="$(go version 2>/dev/null | awk '{print $3}' | sed 's/go//')" + if [[ "$(printf '%s\n' "$go_version" "$current_go" | sort -V | head -1)" == "$go_version" ]]; then + info " Go $current_go already installed." + need_go=false + fi + fi + + if $need_go; then + machine="$(uname -m)" + case "$machine" in + x86_64) goarch="amd64" ;; + aarch64) goarch="arm64" ;; + armv7l) goarch="armv6l" ;; + *) goarch="amd64" ;; + esac + go_url="https://go.dev/dl/go${go_version}.linux-${goarch}.tar.gz" + info " Downloading Go ${go_version} (${goarch})..." + need_cmd wget + wget -q --show-progress -O /tmp/go.tar.gz "$go_url" + rm -rf /usr/local/go + tar -C /usr/local -xzf /tmp/go.tar.gz + rm -f /tmp/go.tar.gz + echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh + chmod +x /etc/profile.d/go.sh + fi + + export PATH=$PATH:/usr/local/go/bin + go version +} + +build_binary() { + info "[3/7] Building new sshpanel binary..." + cd "$SOURCE_DIR" + export GOPATH=/tmp/gopath_sshpanel + export GOCACHE=/tmp/gocache_sshpanel + + BUILD_COMMIT="$(git -C "$SOURCE_DIR" rev-parse HEAD 2>/dev/null || true)" + BUILD_BRANCH="${UPDATE_REF:-$(git -C "$SOURCE_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)}" + BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + BUILD_REPO_URL="DragonCoreSSH-CLI local release" + [[ -n "$BUILD_COMMIT" ]] || BUILD_COMMIT="unknown" + [[ -n "$BUILD_BRANCH" && "$BUILD_BRANCH" != "HEAD" ]] || BUILD_BRANCH="main" + + go mod download + go mod tidy + go build -ldflags="-s -w -X main.buildCommit=$BUILD_COMMIT -X main.buildBranch=$BUILD_BRANCH -X main.buildTime=$BUILD_TIME" -o /tmp/sshpanel_new . + info " Build commit: $BUILD_COMMIT ($BUILD_BRANCH)" + info " Build complete." +} + +stop_service() { + info "[4/7] Stopping service..." + if "$SYSTEMCTL_BIN" is-active --quiet "$SERVICE_NAME" 2>/dev/null; then + "$SYSTEMCTL_BIN" stop "$SERVICE_NAME" + RESTART_NEEDED=true + info " $SERVICE_NAME stopped." + else + RESTART_NEEDED=false + warn " $SERVICE_NAME was not running." + fi +} + +copy_optional_script() { + local name mode + name="$1" + mode="$2" + if [[ -f "$SOURCE_DIR/$name" ]]; then + cp "$SOURCE_DIR/$name" "$INSTALL_DIR/$name" + chmod "$mode" "$INSTALL_DIR/$name" + info " Updated $name" + fi +} + +apply_update() { + info "[5/7] Applying update..." + + mkdir -p "$INSTALL_DIR/logs" "$INSTALL_DIR/certs" + ensure_log_tmpfs_mount + + if [[ -f "$INSTALL_DIR/sshpanel" ]]; then + cp "$INSTALL_DIR/sshpanel" "$INSTALL_DIR/sshpanel.bak" + info " Old binary backed up to $INSTALL_DIR/sshpanel.bak" + fi + + mv /tmp/sshpanel_new "$INSTALL_DIR/sshpanel" + chmod 755 "$INSTALL_DIR/sshpanel" + info " Binary updated." + + printf '%s\n' "$BUILD_COMMIT" > "$INSTALL_DIR/.installed_commit" + printf '%s\n' "$BUILD_BRANCH" > "$INSTALL_DIR/.installed_branch" + printf '%s\n' "$BUILD_TIME" > "$INSTALL_DIR/.installed_build_time" + printf '%s\n' "$BUILD_REPO_URL" > "$INSTALL_DIR/.installed_repo_url" + chmod 0644 "$INSTALL_DIR/.installed_commit" "$INSTALL_DIR/.installed_branch" "$INSTALL_DIR/.installed_build_time" + chmod 0600 "$INSTALL_DIR/.installed_repo_url" + info " Build metadata updated." + + install -m 700 "$SOURCE_DIR/dragoncore_cli.py" "$INSTALL_DIR/dragoncore_cli.py" + ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/dragoncore + if [[ ( -e /usr/local/bin/menu || -L /usr/local/bin/menu ) && "$(readlink -f /usr/local/bin/menu 2>/dev/null || true)" != "$INSTALL_DIR/dragoncore_cli.py" ]]; then + MENU_BACKUP="/usr/local/bin/menu.backup.$(date +%s%N)" + mv /usr/local/bin/menu "$MENU_BACKUP" + warn " Previous menu command saved to $MENU_BACKUP" + fi + ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/menu + info " DragonCoreSSH CLI updated." + + copy_optional_script "update.sh" 700 + copy_optional_script "install.sh" 700 + + # Keep a local copy of the latest source for easier support and future updates. + if [[ "$SOURCE_DIR" != "$SOURCE_CACHE_DIR" ]]; then + mkdir -p "$SOURCE_CACHE_DIR" + rsync -a --delete --exclude '.git' "$SOURCE_DIR/" "$SOURCE_CACHE_DIR/" + info " Source files copied to $SOURCE_CACHE_DIR" + fi + + [[ -f "$INSTALL_DIR/banner.txt" ]] || touch "$INSTALL_DIR/banner.txt" +} + +patch_configs() { + info "[6/7] Patching config files without overwriting user settings..." + + local cfg xcfg + cfg="$INSTALL_DIR/config.json" + xcfg="$INSTALL_DIR/xray_config.json" + + native_xcfg="$INSTALL_DIR/xray_native_config.json" + if [[ ! -f "$native_xcfg" && -f "$xcfg" ]]; then + cp -f "$xcfg" "$native_xcfg" + chmod 600 "$native_xcfg" || true + info " Created independent native Xray config: $native_xcfg" + fi + + if [[ -f "$cfg" ]]; then + python3 - "$cfg" <<'PYEOF' +import ipaddress, json, sys +path = sys.argv[1] +try: + with open(path) as f: + d = json.load(f) +except Exception as e: + print(f"[!] Could not parse {path}: {e}") + sys.exit(0) +changed = False +if 'banner_file' not in d: + d['banner_file'] = '/opt/sshpanel/banner.txt' + changed = True +local_ssh = str(d.get('local_ssh_listen') or '').strip() +local_ssh_valid = False +try: + if local_ssh.startswith('['): + end = local_ssh.index(']') + host = local_ssh[1:end] + if local_ssh[end + 1:end + 2] != ':': + raise ValueError('missing port') + port = int(local_ssh[end + 2:]) + else: + host, port_text = local_ssh.rsplit(':', 1) + port = int(port_text) + local_ssh_valid = ipaddress.ip_address(host).is_loopback and 1 <= port <= 65535 +except (ValueError, IndexError): + pass +if not local_ssh_valid: + d['local_ssh_listen'] = '127.0.0.1:2222' + changed = True +x = d.get('xray') +if isinstance(x, dict): + mode = str(x.get('mode') or '').strip().lower() + if mode not in ('native', 'external'): + x['mode'] = 'native' + x['native'] = True + changed = True + elif mode == 'native' and x.get('native') is not True: + x['native'] = True + changed = True + elif mode == 'external' and x.get('native') is not False: + x['native'] = False + changed = True + x.setdefault('bin_path', '/opt/sshpanel/xray') + x.setdefault('config_file', '/opt/sshpanel/xray_config.json') + x.setdefault('native_config_file', '/opt/sshpanel/xray_native_config.json') +if changed: + with open(path, 'w') as f: + json.dump(d, f, indent=2) + f.write('\n') +PYEOF + info " config.json checked." + fi + + if [[ -f "$xcfg" ]] && grep -q '"geoip:private"' "$xcfg" 2>/dev/null; then + python3 - "$xcfg" <<'PYEOF' +import json, sys +path = sys.argv[1] +try: + with open(path) as f: + d = json.load(f) +except Exception as e: + print(f"[!] Could not parse {path}: {e}") + sys.exit(0) +routing = d.get('routing', {}) +rules = routing.get('rules', []) +new_rules = [r for r in rules if 'geoip:private' not in r.get('ip', [])] +if new_rules != rules: + if new_rules: + d.setdefault('routing', {})['rules'] = new_rules + else: + d.pop('routing', None) + with open(path, 'w') as f: + json.dump(d, f, indent=2) + f.write('\n') +PYEOF + info " Removed geoip:private routing rule from xray_config.json" + fi +} + +dnstt_redirect_is_enabled() { + # Updates must not resurrect this service when an admin intentionally + # disabled/removed it because it can break ip6tables on some machines. + local unit="sshpanel-dnstt-redirect.service" + + if "$SYSTEMCTL_BIN" is-enabled --quiet "$unit" 2>/dev/null; then + return 0 + fi + + return 1 +} + +write_sshpanel_systemd_override() { + local include_dnstt_redirect="${1:-false}" + + mkdir -p /etc/systemd/system/sshpanel.service.d + { + echo "[Unit]" + if [[ "$include_dnstt_redirect" == "true" ]]; then + echo "Wants=sshpanel-dnstt-redirect.service" + echo "After=local-fs.target sshpanel-dnstt-redirect.service" + else + echo "After=local-fs.target" + fi + echo + echo "[Service]" + echo "Environment=PANEL_LOG_FILE=${INSTALL_DIR}/logs/panel.log" + echo "Environment=PANEL_LOG_MAX_BYTES=${PANEL_LOG_MAX_BYTES}" + echo "LimitNOFILE=1048576" + echo "ExecStartPre=" + echo "ExecStartPre=${MKDIR_BIN} -p ${INSTALL_DIR}/logs" + echo "ExecStartPre=${SH_BIN} -c '${MOUNTPOINT_BIN} -q ${INSTALL_DIR}/logs || ${MOUNT_BIN} -t tmpfs -o size=${LOG_TMPFS_SIZE},mode=0755 tmpfs ${INSTALL_DIR}/logs || true'" + echo "ExecStartPre=${SH_BIN} -c '${TOUCH_BIN} ${INSTALL_DIR}/logs/panel.log && ${CHMOD_BIN} 0644 ${INSTALL_DIR}/logs/panel.log || true'" + echo "StandardOutput=journal" + echo "StandardError=journal" + } > /etc/systemd/system/sshpanel.service.d/override.conf +} + +ensure_dnstt_redirect() { + if ! dnstt_redirect_is_enabled; then + warn " sshpanel-dnstt-redirect is disabled or removed; update will not recreate or enable it." + write_sshpanel_systemd_override false + "$SYSTEMCTL_BIN" daemon-reload + return 0 + fi + + info " Ensuring DNSTT DNS redirect service exists..." + cat > /usr/local/sbin/sshpanel-dnstt-redirect.sh <<'EOS' +#!/bin/bash +set -euo pipefail +DNS_UPSTREAM="${DNS_UPSTREAM:-1.1.1.1}" +DNSTT_PORT="${DNSTT_PORT:-5300}" + +if command -v systemctl >/dev/null 2>&1; then + systemctl disable --now systemd-resolved.service >/dev/null 2>&1 || true +fi +rm -f /etc/resolv.conf +printf 'nameserver %s\n' "$DNS_UPSTREAM" > /etc/resolv.conf + +if command -v ufw >/dev/null 2>&1; then + ufw allow 53/udp >/dev/null 2>&1 || true +fi +if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then + firewall-cmd --permanent --add-port=53/udp >/dev/null 2>&1 || true + firewall-cmd --reload >/dev/null 2>&1 || true +fi + +add_iptables_rule() { + local bin="$1" chain="$2" + "$bin" -t nat -C "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" 2>/dev/null \ + || "$bin" -t nat -A "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" +} + +if command -v iptables >/dev/null 2>&1; then + add_iptables_rule iptables PREROUTING +fi +if command -v ip6tables >/dev/null 2>&1; then + add_iptables_rule ip6tables PREROUTING || true +fi +if ! command -v iptables >/dev/null 2>&1 && command -v nft >/dev/null 2>&1; then + nft add table inet sshpanel_nat 2>/dev/null || true + nft 'add chain inet sshpanel_nat prerouting { type nat hook prerouting priority dstnat; policy accept; }' 2>/dev/null || true + nft list chain inet sshpanel_nat prerouting 2>/dev/null | grep -q "udp dport 53 redirect to :$DNSTT_PORT" \ + || nft add rule inet sshpanel_nat prerouting udp dport 53 redirect to :"$DNSTT_PORT" +fi +EOS + chmod +x /usr/local/sbin/sshpanel-dnstt-redirect.sh + + cat > /etc/systemd/system/sshpanel-dnstt-redirect.service <<'EOF2' +[Unit] +Description=SSH Panel DNSTT DNS redirect (UDP 53 to 5300) +After=network.target +Before=sshpanel.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/sshpanel-dnstt-redirect.sh +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +EOF2 + + write_sshpanel_systemd_override true + + "$SYSTEMCTL_BIN" daemon-reload + "$SYSTEMCTL_BIN" enable --now sshpanel-dnstt-redirect.service || warn "DNSTT redirect service failed. Check: journalctl -u sshpanel-dnstt-redirect -e" +} + +restart_service() { + info "[7/7] Restarting service..." + ensure_dnstt_redirect + + if $RESTART_NEEDED; then + info " Starting $SERVICE_NAME after update..." + else + warn " $SERVICE_NAME was not running before update; starting it now." + fi + + "$SYSTEMCTL_BIN" start "$SERVICE_NAME" + sleep 2 + if "$SYSTEMCTL_BIN" is-active --quiet "$SERVICE_NAME"; then + info " $SERVICE_NAME is running." + else + warn " $SERVICE_NAME failed to start. Check logs:" + warn " journalctl -u $SERVICE_NAME -n 50 --no-pager" + if [[ -f "$INSTALL_DIR/sshpanel.bak" ]]; then + warn " Restore command:" + warn " cp $INSTALL_DIR/sshpanel.bak $INSTALL_DIR/sshpanel && systemctl start $SERVICE_NAME" + fi + exit 1 + fi +} + +# Pre-flight +info "[0/7] Pre-flight checks..." +require_systemd +detect_pkg_manager +set_update_deps +ensure_update_dependencies +[[ -d "$INSTALL_DIR" ]] || error "Install dir $INSTALL_DIR not found. Run install.sh first." +[[ -f "$INSTALL_DIR/.env" ]] || error "$INSTALL_DIR/.env not found. Run install.sh first." +need_cmd python3 +need_cmd rsync +need_cmd wget + +info " Install dir : $INSTALL_DIR" +info " Cache dir : $SOURCE_CACHE_DIR" +info " Package manager : $PKG_MANAGER" +info " Service manager : systemd" + +prepare_source_from_git +install_go_if_needed +build_binary +stop_service +apply_update +patch_configs +restart_service + +echo "" +echo -e "${GREEN}==========================================${NC}" +echo -e "${GREEN} Update complete! ${NC}" +echo -e "${GREEN}==========================================${NC}" +echo "" +echo -e " Updated from: ${YELLOW}${REPO_URL}${NC}" +echo -e " Source ref : ${YELLOW}${UPDATE_REF}${NC}" +echo -e " Source cache: ${YELLOW}${SOURCE_CACHE_DIR}${NC}" +echo -e " Logs : ${YELLOW}journalctl -u ${SERVICE_NAME} -f${NC}" +echo -e " ${YELLOW}tail -f ${INSTALL_DIR}/logs/panel.log${NC}" +echo -e " Backup : ${YELLOW}${INSTALL_DIR}/sshpanel.bak${NC}" +echo "" +echo -e "${YELLOW}Updated:${NC}" +echo -e " - sshpanel binary" +echo -e " - DragonCoreSSH CLI and API" +echo -e " - update.sh / install.sh / helper scripts when available" +echo "" +echo -e "${YELLOW}Preserved:${NC}" +echo -e " - .env" +echo -e " - config.json" +echo -e " - xray_config.json" +echo -e " - SSH keys, certs, logs, database and users" +echo "" diff --git a/update_status.go b/update_status.go new file mode 100644 index 0000000..fa060e2 --- /dev/null +++ b/update_status.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/url" + "os" + "os/exec" + "runtime/debug" + "strings" + "sync" + "time" +) + +const ( + defaultUpdateRepoURL = "https://git.dr2.site/penguinehis/DragonCoreSSH-NewWEB.git" + defaultUpdateBranch = "main" + updateStatusCacheTTL = 5 * time.Minute + updateCheckTimeout = 12 * time.Second +) + +// These values are injected by install.sh/update.sh with -ldflags. The +// runtime/debug fallback keeps the endpoint useful for normal git builds. +var ( + buildCommit = "" + buildBranch = "" + buildTime = "" + buildRepoURL = "" +) + +type updateStatusResponse struct { + Status string `json:"status"` + UpToDate bool `json:"up_to_date"` + UpdateAvailable bool `json:"update_available"` + LocalModified bool `json:"local_modified"` + CurrentCommit string `json:"current_commit,omitempty"` + CurrentCommitShort string `json:"current_commit_short,omitempty"` + LatestCommit string `json:"latest_commit,omitempty"` + LatestCommitShort string `json:"latest_commit_short,omitempty"` + Branch string `json:"branch"` + BuildTime string `json:"build_time,omitempty"` + RepoURL string `json:"repo_url"` + RepoWebURL string `json:"repo_web_url"` + CheckedAt string `json:"checked_at"` + Cached bool `json:"cached"` + Error string `json:"error,omitempty"` +} + +var updateStatusCache struct { + sync.Mutex + checkedAt time.Time + response updateStatusResponse +} + +func handleUpdateStatus(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + _ = json.NewEncoder(w).Encode(map[string]string{"error": "method not allowed"}) + return + } + + force := r.URL.Query().Get("refresh") == "1" + resp := getUpdateStatus(r.Context(), force) + _ = json.NewEncoder(w).Encode(resp) +} + +func getUpdateStatus(parent context.Context, force bool) updateStatusResponse { + updateStatusCache.Lock() + defer updateStatusCache.Unlock() + + if !force && !updateStatusCache.checkedAt.IsZero() && time.Since(updateStatusCache.checkedAt) < updateStatusCacheTTL { + resp := updateStatusCache.response + resp.Cached = true + return resp + } + + resp := checkRemoteUpdate(parent) + updateStatusCache.checkedAt = time.Now() + updateStatusCache.response = resp + return resp +} + +func checkRemoteUpdate(parent context.Context) updateStatusResponse { + repoURL := firstNonEmptyTrimmed( + strings.TrimSpace(os.Getenv("DRAGON_UPDATE_REPO_URL")), + readSingleLineFile("/opt/sshpanel/.installed_repo_url"), + strings.TrimSpace(buildRepoURL), + defaultUpdateRepoURL, + ) + branch := firstNonEmptyTrimmed( + strings.TrimSpace(os.Getenv("DRAGON_UPDATE_BRANCH")), + strings.TrimSpace(buildBranch), + readSingleLineFile("/opt/sshpanel/.installed_branch"), + defaultUpdateBranch, + ) + currentCommit, localModified, resolvedBuildTime := resolveCurrentBuildInfo() + if resolvedBuildTime == "" { + resolvedBuildTime = readSingleLineFile("/opt/sshpanel/.installed_build_time") + } + if currentCommit == "" { + currentCommit = normalizeGitCommit(readSingleLineFile("/opt/sshpanel/.installed_commit")) + } + + now := time.Now().UTC().Format(time.RFC3339) + resp := updateStatusResponse{ + Status: "unknown", + CurrentCommit: currentCommit, + CurrentCommitShort: shortCommit(currentCommit), + Branch: branch, + BuildTime: resolvedBuildTime, + RepoURL: safeRepoURL(repoURL), + RepoWebURL: repoWebURL(repoURL), + CheckedAt: now, + LocalModified: localModified, + } + + ctx, cancel := context.WithTimeout(parent, updateCheckTimeout) + defer cancel() + + latestCommit, err := queryRemoteCommit(ctx, repoURL, branch) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + resp.Error = "remote update check timed out" + } else { + resp.Error = "could not read the remote Git branch" + } + return resp + } + + resp.LatestCommit = latestCommit + resp.LatestCommitShort = shortCommit(latestCommit) + + if currentCommit == "" { + resp.Error = "current build commit is unavailable" + return resp + } + + resp.Status, resp.UpToDate, resp.UpdateAvailable = classifyUpdateStatus(currentCommit, latestCommit, localModified) + return resp +} + +func classifyUpdateStatus(currentCommit, latestCommit string, localModified bool) (status string, upToDate bool, updateAvailable bool) { + if currentCommit == "" || latestCommit == "" { + return "unknown", false, false + } + if strings.EqualFold(currentCommit, latestCommit) { + if localModified { + return "local_changes", false, false + } + return "up_to_date", true, false + } + return "update_available", false, true +} + +func queryRemoteCommit(ctx context.Context, repoURL, branch string) (string, error) { + cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", "--heads", repoURL, "refs/heads/"+branch) + cmd.Env = append(os.Environ(), + "GIT_TERMINAL_PROMPT=0", + "GIT_ASKPASS=/bin/false", + ) + out, err := cmd.Output() + if err != nil { + return "", err + } + fields := strings.Fields(string(out)) + if len(fields) < 2 { + return "", errors.New("invalid git ls-remote response") + } + commit := normalizeGitCommit(fields[0]) + if commit == "" { + return "", errors.New("invalid remote commit") + } + return commit, nil +} + +func resolveCurrentBuildInfo() (commit string, modified bool, builtAt string) { + commit = normalizeGitCommit(buildCommit) + builtAt = strings.TrimSpace(buildTime) + + info, ok := debug.ReadBuildInfo() + if !ok { + return commit, false, builtAt + } + for _, setting := range info.Settings { + switch setting.Key { + case "vcs.revision": + if commit == "" { + commit = normalizeGitCommit(setting.Value) + } + case "vcs.modified": + modified = strings.EqualFold(setting.Value, "true") + case "vcs.time": + if builtAt == "" { + builtAt = strings.TrimSpace(setting.Value) + } + } + } + return commit, modified, builtAt +} + +func normalizeGitCommit(value string) string { + value = strings.TrimSpace(value) + if strings.EqualFold(value, "unknown") || len(value) < 7 || len(value) > 64 { + return "" + } + for _, r := range value { + if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) { + return "" + } + } + return strings.ToLower(value) +} + +func shortCommit(commit string) string { + if len(commit) <= 12 { + return commit + } + return commit[:12] +} + +func readSingleLineFile(path string) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + line := strings.TrimSpace(string(data)) + if idx := strings.IndexByte(line, '\n'); idx >= 0 { + line = strings.TrimSpace(line[:idx]) + } + return line +} + +func firstNonEmptyTrimmed(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +func safeRepoURL(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return strings.TrimSpace(raw) + } + u.User = nil + return u.String() +} + +func repoWebURL(raw string) string { + value := safeRepoURL(raw) + return strings.TrimSuffix(value, ".git") +} diff --git a/update_status_test.go b/update_status_test.go new file mode 100644 index 0000000..0ff89bb --- /dev/null +++ b/update_status_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestNormalizeGitCommit(t *testing.T) { + valid := "CF49340B9A1234567890ABCDEF1234567890ABCD" + got := normalizeGitCommit(valid) + want := "cf49340b9a1234567890abcdef1234567890abcd" + if got != want { + t.Fatalf("normalizeGitCommit() = %q, want %q", got, want) + } + for _, value := range []string{"", "unknown", "xyz1234", "123 4567", "123456"} { + if got := normalizeGitCommit(value); got != "" { + t.Fatalf("normalizeGitCommit(%q) = %q, want empty", value, got) + } + } +} + +func TestClassifyUpdateStatus(t *testing.T) { + const current = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + const latest = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + status, upToDate, updateAvailable := classifyUpdateStatus(current, current, false) + if status != "up_to_date" || !upToDate || updateAvailable { + t.Fatalf("same clean commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable) + } + + status, upToDate, updateAvailable = classifyUpdateStatus(current, current, true) + if status != "local_changes" || upToDate || updateAvailable { + t.Fatalf("modified commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable) + } + + status, upToDate, updateAvailable = classifyUpdateStatus(current, latest, false) + if status != "update_available" || upToDate || !updateAvailable { + t.Fatalf("different commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable) + } +} + +func TestRepoWebURLRemovesCredentialsAndGitSuffix(t *testing.T) { + got := repoWebURL("https://user:secret@git.example.test/owner/repo.git") + want := "https://git.example.test/owner/repo" + if got != want { + t.Fatalf("repoWebURL() = %q, want %q", got, want) + } +} + +func TestQueryRemoteCommit(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell-script git stub is Unix-specific") + } + const want = "cf49340b9a1234567890abcdef1234567890abcd" + dir := t.TempDir() + gitPath := filepath.Join(dir, "git") + script := "#!/bin/sh\nprintf '%s\\trefs/heads/main\\n' '" + want + "'\n" + if err := os.WriteFile(gitPath, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + + got, err := queryRemoteCommit(context.Background(), "https://git.example.test/owner/repo.git", "main") + if err != nil { + t.Fatalf("queryRemoteCommit() error = %v", err) + } + if got != want { + t.Fatalf("queryRemoteCommit() = %q, want %q", got, want) + } +} diff --git a/vnstat_api.go b/vnstat_api.go new file mode 100644 index 0000000..cf85a9d --- /dev/null +++ b/vnstat_api.go @@ -0,0 +1,366 @@ +package main + +import ( + "context" + "encoding/json" + "log" + "net/http" + "strconv" + "sync" + "time" +) + +type IfaceUsageDelta struct { + Iface string + RxBytes uint64 + TxBytes uint64 + At time.Time +} + +var ifaceUsagePending = struct { + mu sync.Mutex + m map[string]ifaceCounters +}{m: make(map[string]ifaceCounters)} + +func addPendingIfaceUsage(iface string, rxBytes, txBytes uint64) { + if isIgnoredInterface(iface) || (rxBytes == 0 && txBytes == 0) { + return + } + ifaceUsagePending.mu.Lock() + defer ifaceUsagePending.mu.Unlock() + p := ifaceUsagePending.m[iface] + p.RxBytes += rxBytes + p.TxBytes += txBytes + ifaceUsagePending.m[iface] = p +} + +func flushPendingIfaceUsage(at time.Time) []IfaceUsageDelta { + ifaceUsagePending.mu.Lock() + defer ifaceUsagePending.mu.Unlock() + if len(ifaceUsagePending.m) == 0 { + return nil + } + deltas := make([]IfaceUsageDelta, 0, len(ifaceUsagePending.m)) + for iface, ctrs := range ifaceUsagePending.m { + if isIgnoredInterface(iface) { + continue + } + deltas = append(deltas, IfaceUsageDelta{Iface: iface, RxBytes: ctrs.RxBytes, TxBytes: ctrs.TxBytes, At: at}) + } + ifaceUsagePending.m = make(map[string]ifaceCounters) + return deltas +} + +func restorePendingIfaceUsage(deltas []IfaceUsageDelta) { + ifaceUsagePending.mu.Lock() + defer ifaceUsagePending.mu.Unlock() + for _, d := range deltas { + if isIgnoredInterface(d.Iface) { + continue + } + p := ifaceUsagePending.m[d.Iface] + p.RxBytes += d.RxBytes + p.TxBytes += d.TxBytes + ifaceUsagePending.m[d.Iface] = p + } +} + +func clearPendingIfaceUsage() { + ifaceUsagePending.mu.Lock() + ifaceUsagePending.m = make(map[string]ifaceCounters) + ifaceUsagePending.mu.Unlock() +} + +type VnstatUsageRow struct { + Iface string `json:"iface"` + Period string `json:"period"` + RxBytes uint64 `json:"rx_bytes"` + TxBytes uint64 `json:"tx_bytes"` + TotalBytes uint64 `json:"total_bytes"` +} + +type VnstatDTO struct { + Daily []VnstatUsageRow `json:"daily"` + Monthly []VnstatUsageRow `json:"monthly"` + UpdatedAt time.Time `json:"updated_at"` + TodayPeriod string `json:"today_period"` + MonthPeriod string `json:"month_period"` + TodayTotalBytes uint64 `json:"today_total_bytes"` + MonthTotalBytes uint64 `json:"month_total_bytes"` + InterfaceCount int `json:"interface_count"` +} + +func (s *Store) EnsureIfaceUsageTables(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS ssh_iface_daily_usage ( + usage_date DATE NOT NULL, + iface TEXT NOT NULL, + rx_bytes BIGINT NOT NULL DEFAULT 0, + tx_bytes BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (usage_date, iface) + )`, + `CREATE TABLE IF NOT EXISTS ssh_iface_monthly_usage ( + month_start DATE NOT NULL, + iface TEXT NOT NULL, + rx_bytes BIGINT NOT NULL DEFAULT 0, + tx_bytes BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (month_start, iface) + )`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return nil +} + +func (s *Store) UpsertIfaceUsageDeltas(ctx context.Context, deltas []IfaceUsageDelta) error { + if len(deltas) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + for _, d := range deltas { + if isIgnoredInterface(d.Iface) || (d.RxBytes == 0 && d.TxBytes == 0) { + continue + } + at := d.At + if at.IsZero() { + at = time.Now() + } + day := at.Format("2006-01-02") + month := time.Date(at.Year(), at.Month(), 1, 0, 0, 0, 0, at.Location()).Format("2006-01-02") + + if _, err := tx.ExecContext(ctx, ` + INSERT INTO ssh_iface_daily_usage (usage_date, iface, rx_bytes, tx_bytes, updated_at) + VALUES ($1, $2, $3, $4, NOW()) + ON CONFLICT (usage_date, iface) DO UPDATE + SET rx_bytes = ssh_iface_daily_usage.rx_bytes + EXCLUDED.rx_bytes, + tx_bytes = ssh_iface_daily_usage.tx_bytes + EXCLUDED.tx_bytes, + updated_at = NOW()`, + day, d.Iface, d.RxBytes, d.TxBytes); err != nil { + return err + } + + if _, err := tx.ExecContext(ctx, ` + INSERT INTO ssh_iface_monthly_usage (month_start, iface, rx_bytes, tx_bytes, updated_at) + VALUES ($1, $2, $3, $4, NOW()) + ON CONFLICT (month_start, iface) DO UPDATE + SET rx_bytes = ssh_iface_monthly_usage.rx_bytes + EXCLUDED.rx_bytes, + tx_bytes = ssh_iface_monthly_usage.tx_bytes + EXCLUDED.tx_bytes, + updated_at = NOW()`, + month, d.Iface, d.RxBytes, d.TxBytes); err != nil { + return err + } + } + + return tx.Commit() +} + +func (s *Store) LoadIfaceUsage(ctx context.Context, days, months int) (VnstatDTO, error) { + if days <= 0 || days > 366 { + days = 31 + } + if months <= 0 || months > 60 { + months = 12 + } + + now := time.Now() + todayPeriod := now.Format("2006-01-02") + monthPeriod := now.Format("2006-01") + out := VnstatDTO{UpdatedAt: now, TodayPeriod: todayPeriod, MonthPeriod: monthPeriod} + ifaceSet := make(map[string]struct{}) + + dailyRows, err := s.db.QueryContext(ctx, ` + SELECT iface, usage_date::text, rx_bytes, tx_bytes + FROM ssh_iface_daily_usage + WHERE usage_date >= CURRENT_DATE - $1::int + AND iface <> 'lo' + ORDER BY usage_date DESC, iface ASC`, days-1) + if err != nil { + return out, err + } + defer dailyRows.Close() + for dailyRows.Next() { + var r VnstatUsageRow + if err := dailyRows.Scan(&r.Iface, &r.Period, &r.RxBytes, &r.TxBytes); err != nil { + return out, err + } + r.TotalBytes = r.RxBytes + r.TxBytes + out.Daily = append(out.Daily, r) + ifaceSet[r.Iface] = struct{}{} + if r.Period == todayPeriod { + out.TodayTotalBytes += r.TotalBytes + } + } + if err := dailyRows.Err(); err != nil { + return out, err + } + + monthlyRows, err := s.db.QueryContext(ctx, ` + SELECT iface, to_char(month_start, 'YYYY-MM') AS period, rx_bytes, tx_bytes + FROM ssh_iface_monthly_usage + WHERE month_start >= (date_trunc('month', CURRENT_DATE)::date - ($1::int * INTERVAL '1 month')) + AND iface <> 'lo' + ORDER BY month_start DESC, iface ASC`, months-1) + if err != nil { + return out, err + } + defer monthlyRows.Close() + for monthlyRows.Next() { + var r VnstatUsageRow + if err := monthlyRows.Scan(&r.Iface, &r.Period, &r.RxBytes, &r.TxBytes); err != nil { + return out, err + } + r.TotalBytes = r.RxBytes + r.TxBytes + out.Monthly = append(out.Monthly, r) + ifaceSet[r.Iface] = struct{}{} + if r.Period == monthPeriod { + out.MonthTotalBytes += r.TotalBytes + } + } + if err := monthlyRows.Err(); err != nil { + return out, err + } + + out.InterfaceCount = len(ifaceSet) + + return out, nil +} + +func (s *Store) ResetIfaceUsage(ctx context.Context) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `TRUNCATE TABLE ssh_iface_daily_usage, ssh_iface_monthly_usage`); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) ReplaceIfaceTotals(ctx context.Context, rows []IfaceTotals) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `DELETE FROM ssh_iface_totals`); err != nil { + return err + } + for _, r := range rows { + if isIgnoredInterface(r.Iface) { + continue + } + resetAt := r.ResetAt + if resetAt.IsZero() { + resetAt = time.Now() + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO ssh_iface_totals (iface, total_rx_bytes, total_tx_bytes, last_kernel_rx_bytes, last_kernel_tx_bytes, updated_at, reset_at) + VALUES ($1, $2, $3, $4, $5, NOW(), $6)`, + r.Iface, r.TotalRxBytes, r.TotalTxBytes, r.LastKernelRxBytes, r.LastKernelTxBytes, resetAt); err != nil { + return err + } + } + return tx.Commit() +} + +func handleVnstat(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + days := parsePositiveInt(r.URL.Query().Get("days"), 31) + months := parsePositiveInt(r.URL.Query().Get("months"), 12) + data, err := store.LoadIfaceUsage(r.Context(), days, months) + if err != nil { + log.Printf("failed to load vnstat usage: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(data) + } +} + +func handleVnstatReset(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil { + http.Error(w, "database not configured", http.StatusServiceUnavailable) + return + } + if err := store.ResetIfaceUsage(r.Context()); err != nil { + log.Printf("failed to reset vnstat usage: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + clearPendingIfaceUsage() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) + } +} + +func handleResetInterfaceStats(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if store == nil || ifaceTotalsMgr == nil { + http.Error(w, "interface totals persistence not configured", http.StatusServiceUnavailable) + return + } + + netMap, err := readNetDev() + if err != nil { + log.Printf("failed to read interfaces for reset: %v", err) + http.Error(w, "failed to read interfaces", http.StatusInternalServerError) + return + } + rows := ifaceTotalsMgr.ResetAllToKernel(netMap) + if err := store.ReplaceIfaceTotals(r.Context(), rows); err != nil { + log.Printf("failed to reset interface totals: %v", err) + http.Error(w, "db error", http.StatusInternalServerError) + return + } + + stats := getCurrentStats() + for i := range stats.Interfaces { + stats.Interfaces[i].RxBytes = 0 + stats.Interfaces[i].TxBytes = 0 + } + setCurrentStats(stats) + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) + } +} + +func parsePositiveInt(raw string, fallback int) int { + if raw == "" { + return fallback + } + n, err := strconv.Atoi(raw) + if err != nil || n <= 0 { + return fallback + } + return n +} diff --git a/xray_clients.go b/xray_clients.go new file mode 100644 index 0000000..eef47ac --- /dev/null +++ b/xray_clients.go @@ -0,0 +1,432 @@ +package main + +import ( + "context" + "database/sql" + "log" + "time" +) + +// XrayClientMeta holds metadata stored in PostgreSQL for an Xray client. +// Xray's own config only stores uuid/email/level; expiry, display name, +// reseller owner, and connection policy live here. +type XrayClientMeta struct { + UUID string + Name string + Email string + InboundTag string + OwnerUsername string + ExpiresAt *time.Time + MaxConns int + DataQuotaBytes int64 + QuotaAction string + QuotaThrottleMbps int + CreatedAt time.Time + TotalUplinkBytes int64 + TotalDownlinkBytes int64 + LastActive *time.Time + ActiveConnections int +} + +func (s *Store) EnsureXrayClientsSchema(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS xray_clients ( + uuid TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + inbound_tag TEXT NOT NULL DEFAULT '', + owner_username TEXT NOT NULL DEFAULT '', + expires_at TIMESTAMPTZ, + max_conns INT NOT NULL DEFAULT 0, + data_quota_bytes BIGINT NOT NULL DEFAULT 0, + quota_action TEXT NOT NULL DEFAULT 'block', + quota_throttle_mbps INT NOT NULL DEFAULT 1, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + total_uplink_bytes BIGINT NOT NULL DEFAULT 0, + total_downlink_bytes BIGINT NOT NULL DEFAULT 0, + last_active TIMESTAMPTZ, + active_connections INT NOT NULL DEFAULT 0 + )`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS data_quota_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS quota_action TEXT NOT NULL DEFAULT 'block'`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS quota_throttle_mbps INT NOT NULL DEFAULT 1`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS total_uplink_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS total_downlink_bytes BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS last_active TIMESTAMPTZ`, + `ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS active_connections INT NOT NULL DEFAULT 0`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return nil +} + +func (s *Store) UpsertXrayClientMeta(ctx context.Context, m XrayClientMeta) error { + var expiresAt interface{} + if m.ExpiresAt != nil { + expiresAt = *m.ExpiresAt + } + _, err := s.db.ExecContext(ctx, ` + INSERT INTO xray_clients (uuid, name, email, inbound_tag, owner_username, expires_at, max_conns, data_quota_bytes, quota_action, quota_throttle_mbps) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (uuid) DO UPDATE SET + name = EXCLUDED.name, + email = EXCLUDED.email, + inbound_tag = CASE WHEN EXCLUDED.inbound_tag <> '' THEN EXCLUDED.inbound_tag ELSE xray_clients.inbound_tag END, + owner_username = CASE WHEN EXCLUDED.owner_username <> '' THEN EXCLUDED.owner_username ELSE xray_clients.owner_username END, + expires_at = EXCLUDED.expires_at, + max_conns = EXCLUDED.max_conns, + data_quota_bytes = EXCLUDED.data_quota_bytes, + quota_action = EXCLUDED.quota_action, + quota_throttle_mbps = EXCLUDED.quota_throttle_mbps`, + m.UUID, m.Name, m.Email, m.InboundTag, m.OwnerUsername, expiresAt, m.MaxConns, + m.DataQuotaBytes, normalizeQuotaAction(m.QuotaAction), quotaThrottleMbpsOrDefault(m.QuotaThrottleMbps)) + return err +} + +func (s *Store) GetXrayClientMeta(ctx context.Context, uuid string) (*XrayClientMeta, error) { + m := &XrayClientMeta{} + var expiresAt sql.NullTime + var lastActive sql.NullTime + err := s.db.QueryRowContext(ctx, ` + SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at, + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0) + FROM xray_clients WHERE uuid = $1`, uuid). + Scan(&m.UUID, &m.Name, &m.Email, &m.InboundTag, &m.OwnerUsername, &expiresAt, &m.MaxConns, + &m.DataQuotaBytes, &m.QuotaAction, &m.QuotaThrottleMbps, &m.CreatedAt, + &m.TotalUplinkBytes, &m.TotalDownlinkBytes, &lastActive, &m.ActiveConnections) + if err != nil { + return nil, err + } + if expiresAt.Valid { + m.ExpiresAt = &expiresAt.Time + } + if lastActive.Valid { + m.LastActive = &lastActive.Time + } + return m, nil +} + +func (s *Store) DeleteXrayClientMeta(ctx context.Context, uuid string) error { + // Serialize deletion with the native stats flusher. Otherwise a batch that + // was swapped out just before DELETE could finish afterward and, if the same + // UUID is recreated quickly, apply stale traffic/active deltas to the new row. + xrayMgr.nativeTrafficPersistMu.Lock() + defer xrayMgr.nativeTrafficPersistMu.Unlock() + _, err := s.db.ExecContext(ctx, `DELETE FROM xray_clients WHERE uuid = $1`, uuid) + if err == nil { + xrayMgr.removeNativeQuotaPolicy(uuid) + } + return err +} + +func (s *Store) ListAllXrayClients(ctx context.Context) ([]*XrayClientMeta, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at, + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0) + FROM xray_clients ORDER BY created_at DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + return scanXrayClientMetaRows(rows) +} + +func (s *Store) ListXrayClientsByOwner(ctx context.Context, ownerUsername string) ([]*XrayClientMeta, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at, + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0) + FROM xray_clients WHERE owner_username = $1 ORDER BY created_at DESC`, ownerUsername) + if err != nil { + return nil, err + } + defer rows.Close() + return scanXrayClientMetaRows(rows) +} + +func (s *Store) CountXrayClientsByOwner(ctx context.Context, ownerUsername string) (int, error) { + var n int + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM xray_clients WHERE owner_username = $1`, ownerUsername).Scan(&n) + return n, err +} + +func (s *Store) ListExpiredXrayClients(ctx context.Context) ([]*XrayClientMeta, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at, + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0) + FROM xray_clients WHERE expires_at IS NOT NULL AND expires_at <= NOW()`) + if err != nil { + return nil, err + } + defer rows.Close() + return scanXrayClientMetaRows(rows) +} + +func scanXrayClientMetaRows(rows *sql.Rows) ([]*XrayClientMeta, error) { + var out []*XrayClientMeta + for rows.Next() { + m := &XrayClientMeta{} + var expiresAt sql.NullTime + var lastActive sql.NullTime + if err := rows.Scan(&m.UUID, &m.Name, &m.Email, &m.InboundTag, &m.OwnerUsername, &expiresAt, &m.MaxConns, + &m.DataQuotaBytes, &m.QuotaAction, &m.QuotaThrottleMbps, &m.CreatedAt, + &m.TotalUplinkBytes, &m.TotalDownlinkBytes, &lastActive, &m.ActiveConnections); err != nil { + return nil, err + } + if expiresAt.Valid { + m.ExpiresAt = &expiresAt.Time + } + if lastActive.Valid { + m.LastActive = &lastActive.Time + } + out = append(out, m) + } + return out, rows.Err() +} + +// ResetXrayActiveConnections clears stale online counters after the panel starts. +// Native mode then increments/decrements active_connections for real live streams. +func (s *Store) ResetXrayActiveConnections(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, `UPDATE xray_clients SET active_connections = 0`) + return err +} + +// AddXrayClientTrafficBatch persists native-emulator traffic deltas. It keeps +// totals in PostgreSQL so bandwidth remains visible after panel restarts. +func (s *Store) AddXrayClientTrafficBatch(ctx context.Context, deltas map[string]xrayPendingTraffic) error { + if len(deltas) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + stmt, err := tx.PrepareContext(ctx, ` + UPDATE xray_clients SET + email = CASE WHEN email = '' AND $2 <> '' THEN $2 ELSE email END, + name = CASE WHEN name = '' AND $2 <> '' THEN $2 ELSE name END, + total_uplink_bytes = GREATEST(total_uplink_bytes + GREATEST($3::BIGINT, 0), 0), + total_downlink_bytes = GREATEST(total_downlink_bytes + GREATEST($4::BIGINT, 0), 0), + last_active = NOW() + WHERE uuid = $1`) + if err != nil { + _ = tx.Rollback() + return err + } + defer stmt.Close() + for uuid, d := range deltas { + if uuid == "" || (d.Uplink == 0 && d.Downlink == 0) { + continue + } + if _, err := stmt.ExecContext(ctx, uuid, d.Email, d.Uplink, d.Downlink); err != nil { + _ = tx.Rollback() + return err + } + } + return tx.Commit() +} + +// AddXrayClientActiveBatch persists native online-counter deltas without +// launching a database goroutine/query for every connect and disconnect. +func (s *Store) AddXrayClientActiveBatch(ctx context.Context, deltas map[string]xrayPendingActive) error { + if len(deltas) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + stmt, err := tx.PrepareContext(ctx, ` + UPDATE xray_clients SET + email = CASE WHEN email = '' AND $2 <> '' THEN $2 ELSE email END, + name = CASE WHEN name = '' AND $2 <> '' THEN $2 ELSE name END, + last_active = CASE WHEN $4::BOOLEAN THEN NOW() ELSE last_active END, + active_connections = GREATEST(active_connections + $3::INT, 0) + WHERE uuid = $1`) + if err != nil { + _ = tx.Rollback() + return err + } + defer stmt.Close() + for uuid, d := range deltas { + if uuid == "" || (d.Delta == 0 && !d.Connected) { + continue + } + if _, err := stmt.ExecContext(ctx, uuid, d.Email, d.Delta, d.Connected); err != nil { + _ = tx.Rollback() + return err + } + } + return tx.Commit() +} + +func countOwnedXrayClients(ctx context.Context, store *Store, ownerUsername string) int { + if store == nil || ownerUsername == "" { + return 0 + } + n, err := store.CountXrayClientsByOwner(ctx, ownerUsername) + if err != nil { + log.Printf("count xray clients for %s: %v", ownerUsername, err) + return 0 + } + return n +} + +func countOwnedQuota(ctx context.Context, store *Store, ownerUsername string) int { + return countOwnedUsers(ownerUsername) + countOwnedXrayClients(ctx, store, ownerUsername) +} + +func removeOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) { + if store == nil || ownerUsername == "" { + return + } + clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername) + if err != nil { + log.Printf("xray owner cleanup: list %s: %v", ownerUsername, err) + return + } + needRestart := false + for _, m := range clients { + if m.InboundTag != "" { + if err := xrayMgr.RemoveXrayClient(m.InboundTag, m.UUID); err != nil { + log.Printf("xray owner cleanup: remove %s from %s: %v", m.UUID, m.InboundTag, err) + } else { + needRestart = true + } + } + if err := store.DeleteXrayClientMeta(ctx, m.UUID); err != nil { + log.Printf("xray owner cleanup: delete meta %s: %v", m.UUID, err) + } + } + if needRestart { + xrayMgr.restartIfExternalRunning() + } +} + +// suspendOwnerXrayClients revokes transport access while preserving metadata, +// expiry, traffic and quota. This makes reseller suspension/renewal reversible. +func suspendOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) { + if store == nil || ownerUsername == "" { + return + } + clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername) + if err != nil { + log.Printf("xray owner suspension: list %s: %v", ownerUsername, err) + return + } + changed := false + for _, m := range clients { + xrayMgr.disconnectNativeClient(m.UUID) + if m.InboundTag == "" { + continue + } + if err := xrayMgr.RemoveXrayClient(m.InboundTag, m.UUID); err != nil { + log.Printf("xray owner suspension: remove %s from %s: %v", m.UUID, m.InboundTag, err) + continue + } + changed = true + } + if changed { + xrayMgr.restartIfExternalRunning() + } +} + +// restoreOwnerXrayClients reactivates non-expired clients after reseller renewal. +func restoreOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) { + if store == nil || ownerUsername == "" { + return + } + clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername) + if err != nil { + log.Printf("xray owner restore: list %s: %v", ownerUsername, err) + return + } + now := time.Now() + changed := false + for _, m := range clients { + if m.InboundTag == "" || (m.ExpiresAt != nil && !m.ExpiresAt.After(now)) { + continue + } + email := m.Email + if email == "" { + email = m.UUID + } + if err := xrayMgr.EnsureXrayClient(m.InboundTag, m.UUID, email); err != nil { + log.Printf("xray owner restore: add %s to %s: %v", m.UUID, m.InboundTag, err) + continue + } + xrayMgr.setNativeQuotaPolicy(m) + changed = true + } + if changed { + xrayMgr.restartIfExternalRunning() + } +} + +// startXrayClientExpiryChecker runs a background goroutine that removes expired +// Xray clients from both the config file and the database every 5 minutes. +func startXrayClientExpiryChecker(store *Store) { + if store == nil { + return + } + go func() { + ticker := time.NewTicker(5 * time.Minute) + defer ticker.Stop() + for range ticker.C { + expireXrayClientsOnce(store) + } + }() +} + +func expireXrayClientsOnce(store *Store) { + if store == nil { + return + } + ctx := context.Background() + expired, err := store.ListExpiredXrayClients(ctx) + if err != nil { + log.Printf("xray expiry checker: list error: %v", err) + return + } + needRestart := false + for _, m := range expired { + tag := m.InboundTag + xrayMgr.disconnectNativeClient(m.UUID) + if tag != "" { + if err := xrayMgr.RemoveXrayClient(tag, m.UUID); err != nil { + log.Printf("xray expiry: remove %s from %s: %v", m.UUID, tag, err) + } else { + needRestart = true + } + } + if err := store.DeleteXrayClientMeta(ctx, m.UUID); err != nil { + log.Printf("xray expiry: delete meta %s: %v", m.UUID, err) + } + log.Printf("xray expiry: removed expired client %q (%s) from inbound %s", m.Name, m.UUID, tag) + } + if needRestart { + xrayMgr.restartIfExternalRunning() + } +} + +// ResetXrayClientTraffic clears a client's persistent usage without removing +// the account or changing its expiry/quota policy. +func (s *Store) ResetXrayClientTraffic(ctx context.Context, uuid string) error { + if s == nil || uuid == "" { + return nil + } + _, err := s.db.ExecContext(ctx, ` + UPDATE xray_clients SET + total_uplink_bytes = 0, + total_downlink_bytes = 0, + last_active = NULL + WHERE uuid = $1`, uuid) + return err +} diff --git a/xray_config_store.go b/xray_config_store.go new file mode 100644 index 0000000..257f0d8 --- /dev/null +++ b/xray_config_store.go @@ -0,0 +1,145 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "strings" +) + +// EnsureXrayConfigSchema creates the DB table used as the canonical store for +// Xray JSON configs. The config_file path is used as a stable key so local and +// remote nodes can keep independent configs in the same database if needed. +func (s *Store) EnsureXrayConfigSchema(ctx context.Context) error { + stmts := []string{ + `CREATE TABLE IF NOT EXISTS xray_configs ( + config_key TEXT PRIMARY KEY, + config_json JSONB NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `ALTER TABLE xray_configs ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`, + } + for _, stmt := range stmts { + if _, err := s.db.ExecContext(ctx, stmt); err != nil { + return err + } + } + return nil +} + +func (s *Store) GetXrayConfig(ctx context.Context, configKey string) ([]byte, bool, error) { + if configKey == "" { + configKey = "default" + } + var raw string + err := s.db.QueryRowContext(ctx, `SELECT config_json::text FROM xray_configs WHERE config_key = $1`, configKey).Scan(&raw) + if err != nil { + if err == sql.ErrNoRows { + return nil, false, nil + } + return nil, false, err + } + if !json.Valid([]byte(raw)) { + return nil, false, fmt.Errorf("stored Xray config %q is not valid JSON", configKey) + } + return []byte(raw), true, nil +} + +func (s *Store) UpsertXrayConfig(ctx context.Context, configKey string, data []byte) error { + if configKey == "" { + configKey = "default" + } + if !json.Valid(data) { + return fmt.Errorf("invalid Xray JSON config") + } + _, err := s.db.ExecContext(ctx, ` + INSERT INTO xray_configs (config_key, config_json, updated_at) + VALUES ($1, $2::jsonb, NOW()) + ON CONFLICT (config_key) DO UPDATE SET + config_json = EXCLUDED.config_json, + updated_at = NOW()`, configKey, string(data)) + return err +} + +func (s *Store) ListXrayClientsByInbound(ctx context.Context, inboundTag string) ([]*XrayClientMeta, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns, + COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at, + COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0) + FROM xray_clients WHERE inbound_tag = $1 ORDER BY created_at DESC`, inboundTag) + if err != nil { + return nil, err + } + defer rows.Close() + return scanXrayClientMetaRows(rows) +} + +// ImportXrayClientsFromConfig mirrors client UUIDs found in an existing Xray +// JSON config into xray_clients. This lets native mode inherit users from the +// external Xray config and keeps the DB as the hot-reloadable client index. +// It intentionally preserves owner/expiry/quota fields for existing rows. +func (s *Store) ImportXrayClientsFromConfig(ctx context.Context, data []byte) (int, error) { + if s == nil || len(data) == 0 { + return 0, nil + } + var cfg struct { + Inbounds []struct { + Tag string `json:"tag"` + Protocol string `json:"protocol"` + Settings struct { + Clients []struct { + ID string `json:"id"` + Password string `json:"password"` + Email string `json:"email"` + } `json:"clients"` + Users []struct { + ID string `json:"id"` + Password string `json:"password"` + Email string `json:"email"` + } `json:"users"` + } `json:"settings"` + } `json:"inbounds"` + } + if err := json.Unmarshal(data, &cfg); err != nil { + return 0, err + } + imported := 0 + for _, ib := range cfg.Inbounds { + proto := strings.ToLower(strings.TrimSpace(ib.Protocol)) + if proto != "vless" && proto != "vmess" && proto != "trojan" { + continue + } + inboundTag := strings.TrimSpace(ib.Tag) + configClients := ib.Settings.Clients + if len(ib.Settings.Users) > 0 { + configClients = append(configClients, ib.Settings.Users...) + } + for _, c := range configClients { + uuid := strings.TrimSpace(c.ID) + if uuid == "" { + uuid = strings.TrimSpace(c.Password) + } + if uuid == "" { + continue + } + email := strings.TrimSpace(c.Email) + if email == "" { + email = uuid + } + _, err := s.db.ExecContext(ctx, ` + INSERT INTO xray_clients (uuid, name, email, inbound_tag) + VALUES ($1, $2, $3, $4) + ON CONFLICT (uuid) DO UPDATE SET + email = CASE WHEN xray_clients.email = '' THEN EXCLUDED.email ELSE xray_clients.email END, + name = CASE WHEN xray_clients.name = '' THEN EXCLUDED.name ELSE xray_clients.name END, + inbound_tag = CASE WHEN EXCLUDED.inbound_tag <> '' THEN EXCLUDED.inbound_tag ELSE xray_clients.inbound_tag END`, + uuid, email, email, inboundTag) + if err != nil { + return imported, err + } + imported++ + } + } + return imported, nil +} diff --git a/xray_integration.go b/xray_integration.go new file mode 100644 index 0000000..09ae931 --- /dev/null +++ b/xray_integration.go @@ -0,0 +1,3108 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/exec" + "regexp" + "strconv" + "strings" + "sync" + "syscall" + "time" +) + +// XrayConfig holds Xray process management settings embedded in the main Config. +type XrayConfig struct { + Enabled bool `json:"enabled"` + BinPath string `json:"bin_path"` // external mode only, e.g. /opt/sshpanel/xray + ConfigFile string `json:"config_file"` // external runtime config, e.g. /opt/sshpanel/xray_config.json + NativeConfigFile string `json:"native_config_file,omitempty"` // native emulator config, independent from external xray + + // Mode selects the runtime implementation. Supported values: + // native = run the in-process emulator implemented in this binary + // external = spawn the external /opt/sshpanel/xray binary + // Empty/unknown is normalized to native so older configs do not silently + // keep using the external binary after this build is installed. + Mode string `json:"mode,omitempty"` + + // Native is kept for backward compatibility with older configs/UI payloads. + // New writes should set both Mode and Native. Runtime decisions use UseNative(). + Native bool `json:"native,omitempty"` + + // Optional Xray API endpoint used for online client counters. If empty, + // the panel auto-detects a local inbound tagged "api" from the Xray config. + APIServer string `json:"api_server,omitempty"` // e.g. 127.0.0.1:10085 + // A client is considered online when its Xray stats traffic changed recently. + OnlineWindowSeconds int `json:"online_window_seconds,omitempty"` // default 90 + StatsPollSeconds int `json:"stats_poll_seconds,omitempty"` // default 15 + + // NativeIPStrategy controls native outbound address selection. The native + // runtime defaults to auto dual-stack behavior so IPv6 destinations from + // clients are preserved when the server has IPv6 connectivity. force_ipv4 is + // only kept as an explicit legacy override. + NativeIPStrategy string `json:"native_ip_strategy,omitempty"` // auto | force_ipv4 + + // NativeTuning exposes native-emulator scale/performance knobs in the admin panel. + // These replace the old XRAY_NATIVE_* systemd environment overrides. + NativeTuning *XrayNativeTuning `json:"native_tuning,omitempty"` +} + +const ( + xrayModeNative = "native" + xrayModeExternal = "external" + defaultXrayBinPath = "/opt/sshpanel/xray" + defaultXrayConfigFile = "/opt/sshpanel/xray_config.json" + defaultXrayNativeConfigFile = "/opt/sshpanel/xray_native_config.json" + xrayNativeIPStrategyAuto = "auto" + xrayNativeIPStrategyForce4 = "force_ipv4" +) + +func (c *XrayConfig) NormalizeDefaults() { + if c == nil { + return + } + mode := strings.ToLower(strings.TrimSpace(c.Mode)) + switch mode { + case xrayModeExternal: + c.Mode = xrayModeExternal + c.Native = false + case xrayModeNative: + c.Mode = xrayModeNative + c.Native = true + default: + // Old configs did not have mode/native and used the external binary by + // accident. For the emulator build, make internal/native the safe default. + c.Mode = xrayModeNative + c.Native = true + } + if strings.TrimSpace(c.ConfigFile) == "" { + c.ConfigFile = defaultXrayConfigFile + } + if strings.TrimSpace(c.NativeConfigFile) == "" { + c.NativeConfigFile = defaultXrayNativeConfigFile + } + if strings.TrimSpace(c.BinPath) == "" { + c.BinPath = defaultXrayBinPath + } + switch strings.ToLower(strings.TrimSpace(c.NativeIPStrategy)) { + case "ipv4", "useipv4", "use_ipv4", xrayNativeIPStrategyForce4: + c.NativeIPStrategy = xrayNativeIPStrategyForce4 + default: + c.NativeIPStrategy = xrayNativeIPStrategyAuto + } + tuning := normalizeNativeXrayTuning(c.NativeTuning) + c.NativeTuning = &tuning + applyNativeXrayTuning(c.NativeTuning) +} + +func (c *XrayConfig) NativeForceIPv4() bool { + if c == nil { + return false + } + mode := strings.ToLower(strings.TrimSpace(c.NativeIPStrategy)) + return mode == xrayNativeIPStrategyForce4 || mode == "ipv4" || mode == "useipv4" || mode == "use_ipv4" +} + +func (c *XrayConfig) ModeName() string { + if c == nil { + return "disabled" + } + mode := strings.ToLower(strings.TrimSpace(c.Mode)) + if mode == xrayModeExternal { + return xrayModeExternal + } + if mode == xrayModeNative || c.Native { + return xrayModeNative + } + return xrayModeNative +} + +func (c *XrayConfig) UseNative() bool { + return c != nil && c.ModeName() != xrayModeExternal +} + +func (c *XrayConfig) ActiveConfigFile() string { + if c == nil { + return "" + } + if c.UseNative() { + if strings.TrimSpace(c.NativeConfigFile) != "" { + return strings.TrimSpace(c.NativeConfigFile) + } + return defaultXrayNativeConfigFile + } + if strings.TrimSpace(c.ConfigFile) != "" { + return strings.TrimSpace(c.ConfigFile) + } + return defaultXrayConfigFile +} + +func (c *XrayConfig) ExternalConfigFile() string { + if c == nil { + return "" + } + if strings.TrimSpace(c.ConfigFile) != "" { + return strings.TrimSpace(c.ConfigFile) + } + return defaultXrayConfigFile +} + +// xrayLogRing is a fixed-capacity circular buffer for captured log lines. +type xrayLogRing struct { + mu sync.Mutex + lines []string + pos int +} + +const ( + xrayLogCap = 5000 + xrayForcedLogLevel = "debug" + xrayForcedAccessLogPath = "/dev/stdout" + xrayForcedErrorLogPath = "/dev/stderr" +) + +func (r *xrayLogRing) add(line string) { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.lines) < xrayLogCap { + r.lines = append(r.lines, line) + } else { + r.lines[r.pos] = line + r.pos = (r.pos + 1) % xrayLogCap + } +} + +func (r *xrayLogRing) snapshot() []string { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.lines) == 0 { + return nil + } + out := make([]string, len(r.lines)) + if len(r.lines) < xrayLogCap { + copy(out, r.lines) + } else { + n := copy(out, r.lines[r.pos:]) + copy(out[n:], r.lines[:r.pos]) + } + return out +} + +var xrayLogBuf = &xrayLogRing{} + +// xrayWriter captures writes from the xray subprocess into the log ring buffer +// and forwards them to stderr so they appear in the process log. +type xrayWriter struct{} + +func (w xrayWriter) Write(p []byte) (int, error) { + text := strings.TrimRight(string(p), "\n") + for _, line := range strings.Split(text, "\n") { + if line != "" { + xrayLogBuf.add(line) + } + } + return os.Stderr.Write(p) +} + +// xrayLogf writes native/runtime Xray debug messages directly to stderr and +// to the in-memory Xray log ring. It intentionally bypasses the global +// standard logger because the panel can run in quiet mode and call +// log.SetOutput(io.Discard). Xray debug logs must remain visible while +// troubleshooting transport issues. +func xrayLogf(format string, args ...interface{}) { + msg := strings.TrimRight(fmt.Sprintf(format, args...), "\n") + if strings.TrimSpace(msg) == "" { + return + } + ts := time.Now().Format("2006/01/02 15:04:05") + for _, line := range strings.Split(msg, "\n") { + if line == "" { + continue + } + full := ts + " " + line + xrayLogBuf.add(full) + _, _ = fmt.Fprintln(os.Stderr, full) + } +} + +// xrayTracef is for very hot transport-level traces such as every XHTTP packet. +// Leaving those on under many QUIC users can bottleneck on journald/stderr and +// make the tunnel appear slow. Enable only when packet-level tracing is needed: +// Enable packet-level tracing from Admin Panel -> Xray Native Scale -> Trace packets. +func xrayTracef(format string, args ...interface{}) { + if !nativeTracePacketsEnabled() { + return + } + xrayLogf(format, args...) +} + +// XrayManager manages the lifecycle of the external xray subprocess. +type XrayManager struct { + mu sync.Mutex + cmd *exec.Cmd + doneCh chan struct{} + cfg *XrayConfig + startTime time.Time + lastErr string + + statsMu sync.RWMutex + statsByEmail map[string]xrayRuntimeStat + lastStatsErr string + lastStatsPoll time.Time + pollStarted bool + rateSamplerStarted bool + + nativeDBMu sync.Mutex + nativeTrafficPersistMu sync.Mutex + nativeTrafficPending map[string]xrayPendingTraffic + nativeActivePending map[string]xrayPendingActive + nativeStatsFlushStarted bool + + nativeQuotaMu sync.RWMutex + nativeQuotaByUUID map[string]*xrayNativeQuotaState +} + +type xrayTrafficCounters struct { + Uplink int64 + Downlink int64 +} + +type xrayRuntimeStat struct { + Email string + Uplink int64 + Downlink int64 + LastActive time.Time + ActiveConnections int +} + +type xrayPendingTraffic struct { + Email string + Uplink int64 + Downlink int64 + State *xrayNativeQuotaState +} + +type xrayPendingActive struct { + Email string + Delta int + Connected bool + State *xrayNativeQuotaState +} + +var xrayMgr = &XrayManager{} + +// initXrayManager stores the config and auto-starts Xray if Enabled is true. +func initXrayManager(cfg *XrayConfig) { + if cfg == nil { + return + } + xrayMgr.mu.Lock() + xrayMgr.cfg = cfg + if err := xrayMgr.bootstrapConfigStoreLocked(); err != nil { + xrayLogf("xray: database config bootstrap failed: %v", err) + } + xrayMgr.mu.Unlock() + + // Reconcile already-expired rows before the runtime loads DB-backed clients. + // The periodic checker intentionally sleeps between passes, so doing one pass + // here closes the startup window in which an expired UUID could reconnect. + expireXrayClientsOnce(statsStore) + xrayMgr.reloadNativeQuotaPolicies() + + // In native mode the in-process emulator records traffic directly, so the + // external `xray api statsquery` poller is not started (it would overwrite + // the native counters with errors from a non-existent CLI endpoint). + xrayMgr.startNativeStatsFlusher() + xrayMgr.startRateSampler() + if !cfg.UseNative() { + xrayMgr.startStatsPoller() + } + + if cfg.Enabled { + if err := xrayMgr.Start(); err != nil { + xrayLogf("xray: auto-start failed: %v", err) + } + } +} + +// isRunning returns true if the subprocess is currently alive. +// Must be called with m.mu held. +func (m *XrayManager) isRunning() bool { + if m.doneCh == nil { + return false + } + select { + case <-m.doneCh: + return false + default: + return true + } +} + +// Start launches the xray subprocess. Returns an error if already running or misconfigured. +func (m *XrayManager) Start() error { + m.mu.Lock() + defer m.mu.Unlock() + + if m.cfg == nil { + return fmt.Errorf("xray not configured") + } + m.cfg.NormalizeDefaults() + if err := m.syncConfigFileFromStoreLocked(); err != nil { + m.lastErr = err.Error() + return err + } + configFile := m.activeConfigFileLocked() + if _, err := m.readConfigLocked(); err != nil && !os.IsNotExist(err) { + m.lastErr = err.Error() + return err + } + + // Native mode: run the in-process emulator instead of the subprocess. + if m.cfg.UseNative() { + if nativeXray.nativeRunning() { + return fmt.Errorf("native xray already running") + } + if err := nativeXray.start(configFile); err != nil { + m.lastErr = err.Error() + return err + } + m.startTime = time.Now() + m.lastErr = "" + return nil + } + + if m.isRunning() { + return fmt.Errorf("xray already running (pid %d)", m.cmd.Process.Pid) + } + if _, err := os.Stat(m.cfg.BinPath); err != nil { + return fmt.Errorf("xray binary not found at %s", m.cfg.BinPath) + } + if changed, err := m.ensureStatsAPIConfigLocked(); err != nil { + return fmt.Errorf("xray stats api check failed: %w", err) + } else if changed { + xrayLogf("xray: repaired Stats API support and forced debug logs in config before start") + } + + args := []string{"run"} + if configFile != "" { + args = append(args, "-c", configFile) + } + + cmd := exec.Command(m.cfg.BinPath, args...) + cmd.Stdout = xrayWriter{} + cmd.Stderr = xrayWriter{} + + if err := cmd.Start(); err != nil { + m.lastErr = err.Error() + return fmt.Errorf("xray start: %w", err) + } + + doneCh := make(chan struct{}) + m.cmd = cmd + m.doneCh = doneCh + m.startTime = time.Now() + m.lastErr = "" + + go func() { + err := cmd.Wait() + close(doneCh) + m.mu.Lock() + if err != nil { + m.lastErr = err.Error() + } + m.mu.Unlock() + xrayLogf("xray: process exited: %v", err) + }() + + xrayLogf("xray: started (pid %d)", cmd.Process.Pid) + return nil +} + +// Stop sends SIGTERM and waits up to 5 s before forcing SIGKILL. +func (m *XrayManager) Stop() error { + // Stop both implementations defensively. Mode can change at runtime; relying + // only on the new cfg.Native value can leak the old external subprocess when + // switching external -> native, or leave native listeners bound when switching + // native -> external. + nativeXray.stop() + m.flushNativeStatsToDB() + + m.mu.Lock() + if !m.isRunning() { + m.mu.Unlock() + return nil + } + doneCh := m.doneCh + cmd := m.cmd + m.mu.Unlock() + + _ = cmd.Process.Signal(syscall.SIGTERM) + + select { + case <-doneCh: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + select { + case <-doneCh: + case <-time.After(2 * time.Second): + } + } + xrayLogf("xray: stopped") + return nil +} + +// Restart stops then starts the xray subprocess. +func (m *XrayManager) Restart() error { + if err := m.Stop(); err != nil { + return err + } + return m.Start() +} + +// recordNativeConnect marks a native client stream as online immediately. This +// is more accurate than external Xray's Stats API polling because it knows when +// the decoded VMess/VLESS stream is authenticated and opened. +func (m *XrayManager) recordNativeConnect(uuid, email string, state *xrayNativeQuotaState) { + uuid = strings.TrimSpace(uuid) + email = strings.TrimSpace(email) + if email == "" { + email = uuid + } + if uuid == "" && email == "" { + return + } + now := time.Now() + m.statsMu.Lock() + if m.statsByEmail == nil { + m.statsByEmail = make(map[string]xrayRuntimeStat) + } + key := firstNonEmpty(uuid, email) + st := m.statsByEmail[key] + st.Email = email + st.LastActive = now + st.ActiveConnections++ + m.statsByEmail[key] = st + m.statsMu.Unlock() + + m.queueNativeActiveDelta(uuid, email, 1, true, state) +} + +func (m *XrayManager) recordNativeDisconnect(uuid, email string, state *xrayNativeQuotaState) { + uuid = strings.TrimSpace(uuid) + email = strings.TrimSpace(email) + if email == "" { + email = uuid + } + if uuid == "" && email == "" { + return + } + m.statsMu.Lock() + if m.statsByEmail != nil { + key := firstNonEmpty(uuid, email) + st := m.statsByEmail[key] + if st.ActiveConnections > 0 { + st.ActiveConnections-- + } + m.statsByEmail[key] = st + } + m.statsMu.Unlock() + + m.queueNativeActiveDelta(uuid, email, -1, false, state) +} + +func (m *XrayManager) queueNativeActiveDelta(uuid, email string, delta int, connected bool, state *xrayNativeQuotaState) { + if statsStore == nil || uuid == "" || delta == 0 || state == nil { + return + } + // Keep the policy identity stable until the delta is queued. A UUID can be + // deleted and later recreated; an old connection must never decrement or add + // traffic to the replacement account merely because the string key matches. + m.nativeQuotaMu.RLock() + if m.nativeQuotaByUUID[uuid] != state { + m.nativeQuotaMu.RUnlock() + return + } + m.nativeDBMu.Lock() + if m.nativeActivePending == nil { + m.nativeActivePending = make(map[string]xrayPendingActive) + } + p := m.nativeActivePending[uuid] + if p.State != nil && p.State != state { + p = xrayPendingActive{} + } + if p.Email == "" { + p.Email = email + } + p.Delta += delta + p.Connected = p.Connected || connected + p.State = state + m.nativeActivePending[uuid] = p + m.nativeDBMu.Unlock() + m.nativeQuotaMu.RUnlock() +} + +// recordNativeTraffic accumulates in-process byte counters for a client and +// queues DB persistence. Used by the native emulator instead of external +// `xray api statsquery` polling. +func (m *XrayManager) recordNativeTraffic(uuid, email string, up, down int64, generation uint64, state *xrayNativeQuotaState) { + uuid = strings.TrimSpace(uuid) + email = strings.TrimSpace(email) + if email == "" { + email = uuid + } + if email == "" || (up == 0 && down == 0) { + return + } + if state != nil { + // Keep generation validation and queuing in the same critical section as + // resetNativeTrafficAccounting. Otherwise an old meter can validate just + // before a reset and enqueue its bytes immediately after the DB was zeroed. + state.mu.Lock() + defer state.mu.Unlock() + if generation != state.generation { + return + } + } + + // Only DB-backed clients have a native policy state. Config-only clients are + // still shown in runtime stats, but queuing UPDATEs for rows that do not exist + // can make the retry map grow during a database outage. + if statsStore != nil && uuid != "" && state != nil { + m.nativeQuotaMu.RLock() + if m.nativeQuotaByUUID[uuid] != state { + m.nativeQuotaMu.RUnlock() + return + } + m.nativeDBMu.Lock() + if m.nativeTrafficPending == nil { + m.nativeTrafficPending = make(map[string]xrayPendingTraffic) + } + p := m.nativeTrafficPending[uuid] + if p.State != nil && p.State != state { + p = xrayPendingTraffic{} + } + p.Email = email + p.Uplink += up + p.Downlink += down + p.State = state + m.nativeTrafficPending[uuid] = p + m.nativeDBMu.Unlock() + m.nativeQuotaMu.RUnlock() + } + + now := time.Now() + m.statsMu.Lock() + if m.statsByEmail == nil { + m.statsByEmail = make(map[string]xrayRuntimeStat) + } + key := firstNonEmpty(uuid, email) + st := m.statsByEmail[key] + st.Email = email + st.Uplink += up + st.Downlink += down + st.LastActive = now + m.statsByEmail[key] = st + m.statsMu.Unlock() + +} + +func (m *XrayManager) startNativeStatsFlusher() { + m.nativeDBMu.Lock() + if m.nativeStatsFlushStarted { + m.nativeDBMu.Unlock() + return + } + m.nativeStatsFlushStarted = true + m.nativeDBMu.Unlock() + + xrayGo("native xray stats flusher", func() { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for range ticker.C { + m.flushNativeStatsToDB() + m.pruneStaleRuntimeStats() + } + }) +} + +// pruneStaleRuntimeStats drops runtime stat entries for clients that have no +// active connections and have been idle well past the online window. Without +// this, statsByEmail keeps one entry per email/UUID that has ever connected and +// never shrinks. The retention comfortably exceeds the online-detection grace +// window so CountOnlineUsers is unaffected; persistent traffic totals live in +// the DB, so dropping the in-memory counter for a long-offline client is safe. +func (m *XrayManager) pruneStaleRuntimeStats() { + retention := 2 * m.onlineWindow() + if retention < 5*time.Minute { + retention = 5 * time.Minute + } + cutoff := time.Now().Add(-retention) + m.statsMu.Lock() + for email, st := range m.statsByEmail { + if st.ActiveConnections <= 0 && (st.LastActive.IsZero() || st.LastActive.Before(cutoff)) { + delete(m.statsByEmail, email) + } + } + m.statsMu.Unlock() +} + +func (m *XrayManager) flushNativeStatsToDB() { + if statsStore == nil { + return + } + m.nativeTrafficPersistMu.Lock() + defer m.nativeTrafficPersistMu.Unlock() + persistent := m.nativePersistentStates() + m.nativeDBMu.Lock() + for uuid, pending := range m.nativeTrafficPending { + if persistent[uuid] != pending.State { + delete(m.nativeTrafficPending, uuid) + } + } + for uuid, pending := range m.nativeActivePending { + if persistent[uuid] != pending.State { + delete(m.nativeActivePending, uuid) + } + } + pendingTraffic := m.nativeTrafficPending + pendingActive := m.nativeActivePending + m.nativeTrafficPending = nil + m.nativeActivePending = nil + m.nativeDBMu.Unlock() + if len(pendingTraffic) == 0 && len(pendingActive) == 0 { + return + } + + var trafficErr error + if len(pendingTraffic) > 0 { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + trafficErr = statsStore.AddXrayClientTrafficBatch(ctx, pendingTraffic) + cancel() + } + var activeErr error + if len(pendingActive) > 0 { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + activeErr = statsStore.AddXrayClientActiveBatch(ctx, pendingActive) + cancel() + } + + if trafficErr != nil { + xrayLogf("xray native stats: db traffic flush failed: %v", trafficErr) + } + if activeErr != nil { + xrayLogf("xray native stats: db active flush failed: %v", activeErr) + } + if trafficErr != nil || activeErr != nil { + // Put only failed batches back so a successful write is never duplicated. + persistent = m.nativePersistentStates() + m.nativeDBMu.Lock() + if trafficErr != nil && m.nativeTrafficPending == nil { + m.nativeTrafficPending = make(map[string]xrayPendingTraffic) + } + if trafficErr != nil { + for uuid, d := range pendingTraffic { + if persistent[uuid] != d.State { + continue + } + p := m.nativeTrafficPending[uuid] + if p.State != nil && p.State != d.State { + p = xrayPendingTraffic{} + } + if p.Email == "" { + p.Email = d.Email + } + p.Uplink += d.Uplink + p.Downlink += d.Downlink + p.State = d.State + m.nativeTrafficPending[uuid] = p + } + } + if activeErr != nil && m.nativeActivePending == nil { + m.nativeActivePending = make(map[string]xrayPendingActive) + } + if activeErr != nil { + for uuid, d := range pendingActive { + if persistent[uuid] != d.State { + continue + } + p := m.nativeActivePending[uuid] + if p.State != nil && p.State != d.State { + p = xrayPendingActive{} + } + if p.Email == "" { + p.Email = d.Email + } + p.Delta += d.Delta + p.Connected = p.Connected || d.Connected + p.State = d.State + m.nativeActivePending[uuid] = p + } + } + m.nativeDBMu.Unlock() + } +} + +func (m *XrayManager) nativePersistentStates() map[string]*xrayNativeQuotaState { + m.nativeQuotaMu.RLock() + out := make(map[string]*xrayNativeQuotaState, len(m.nativeQuotaByUUID)) + for uuid, state := range m.nativeQuotaByUUID { + out[uuid] = state + } + m.nativeQuotaMu.RUnlock() + return out +} + +// XrayStatusDTO is returned by /api/xray/status. +type XrayStatusDTO struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Mode string `json:"mode"` + Native bool `json:"native"` + PID int `json:"pid,omitempty"` + Uptime string `json:"uptime,omitempty"` + Error string `json:"error,omitempty"` + OnlineUsers int `json:"online_users"` + StatsError string `json:"stats_error,omitempty"` + StatsConfigured bool `json:"stats_configured"` + StatsMissing []string `json:"stats_missing,omitempty"` + APIServer string `json:"api_server,omitempty"` + LastStatsPoll *time.Time `json:"last_stats_poll,omitempty"` + OnlineWindowSec int `json:"online_window_seconds"` +} + +// Status returns a snapshot of the current xray process state. +func (m *XrayManager) Status() XrayStatusDTO { + m.mu.Lock() + native := m.cfg != nil && m.cfg.UseNative() + m.mu.Unlock() + + // Native mode: report the in-process emulator's state. Traffic counters are + // recorded live so there is no CLI poll and no Stats API config to check. + if native { + m.mu.Lock() + s := XrayStatusDTO{Enabled: m.cfg.Enabled, Mode: m.cfg.ModeName(), Native: m.cfg.UseNative()} + if nativeXray.nativeRunning() { + s.Running = true + s.Uptime = time.Since(m.startTime).Round(time.Second).String() + } + if m.lastErr != "" { + s.Error = m.lastErr + } + m.mu.Unlock() + s.OnlineUsers = m.CountOnlineUsers() + s.OnlineWindowSec = int(m.onlineWindow().Seconds()) + s.StatsConfigured = true // in-process metering is always available + return s + } + + m.refreshRuntimeStatsIfStale(3 * time.Second) + m.mu.Lock() + s := XrayStatusDTO{} + if m.cfg != nil { + s.Enabled = m.cfg.Enabled + s.Mode = m.cfg.ModeName() + s.Native = m.cfg.UseNative() + } + if m.isRunning() && m.cmd != nil && m.cmd.Process != nil { + s.Running = true + s.PID = m.cmd.Process.Pid + s.Uptime = time.Since(m.startTime).Round(time.Second).String() + } + if m.lastErr != "" { + s.Error = m.lastErr + } + m.mu.Unlock() + + s.OnlineUsers = m.CountOnlineUsers() + s.OnlineWindowSec = int(m.onlineWindow().Seconds()) + m.statsMu.RLock() + if m.lastStatsErr != "" { + s.StatsError = m.lastStatsErr + } + if !m.lastStatsPoll.IsZero() { + t := m.lastStatsPoll + s.LastStatsPoll = &t + } + m.statsMu.RUnlock() + if check, err := m.CheckStatsAPIConfig(); err == nil { + s.StatsConfigured = check.Configured + s.StatsMissing = check.Missing + s.APIServer = check.APIServer + } else if err != nil { + s.StatsConfigured = false + s.StatsMissing = []string{err.Error()} + } + return s +} + +func (m *XrayManager) pollInterval() time.Duration { + m.mu.Lock() + defer m.mu.Unlock() + sec := 15 + if m.cfg != nil && m.cfg.StatsPollSeconds > 0 { + sec = m.cfg.StatsPollSeconds + } + if sec < 5 { + sec = 5 + } + return time.Duration(sec) * time.Second +} + +func (m *XrayManager) onlineWindow() time.Duration { + m.mu.Lock() + defer m.mu.Unlock() + sec := 90 + if m.cfg != nil && m.cfg.OnlineWindowSeconds > 0 { + sec = m.cfg.OnlineWindowSeconds + } + if sec < 15 { + sec = 15 + } + return time.Duration(sec) * time.Second +} + +func (m *XrayManager) startStatsPoller() { + m.mu.Lock() + if m.pollStarted { + m.mu.Unlock() + return + } + m.pollStarted = true + m.mu.Unlock() + + go func() { + // First sample establishes a baseline. Active Xray users appear online + // after their traffic counters change on a later poll. + for { + m.refreshRuntimeStats() + time.Sleep(m.pollInterval()) + } + }() +} + +// Live per-client speed, derived from the same cumulative counters the panel +// already reports as lifetime traffic. +var xrayBandwidth = newBandwidthSampler(6*time.Second, 45*time.Second) + +const xrayNativeRateSampleInterval = 2 * time.Second + +// startRateSampler keeps xrayBandwidth fresh in native mode, where the +// in-process runtime updates the counters continuously. In external mode the +// counters only move once per stats poll (15s by default), so refreshRuntimeStats +// feeds the sampler at its own cadence instead — sampling faster than the source +// updates would show alternating spikes and zeros. The mode is re-checked on +// every tick because a hot reload can switch it while running. +func (m *XrayManager) startRateSampler() { + m.mu.Lock() + if m.rateSamplerStarted { + m.mu.Unlock() + return + } + m.rateSamplerStarted = true + m.mu.Unlock() + + go func() { + ticker := time.NewTicker(xrayNativeRateSampleInterval) + defer ticker.Stop() + for range ticker.C { + if !m.usesNativeSnapshot() { + continue + } + m.sampleRuntimeRates(time.Now()) + } + }() +} + +func (m *XrayManager) usesNativeSnapshot() bool { + m.mu.Lock() + defer m.mu.Unlock() + return m.cfg != nil && m.cfg.UseNative() +} + +func (m *XrayManager) sampleRuntimeRates(now time.Time) { + type counterSnapshot struct { + key string + uplink int64 + downlink int64 + } + m.statsMu.RLock() + snapshots := make([]counterSnapshot, 0, len(m.statsByEmail)) + for key, st := range m.statsByEmail { + snapshots = append(snapshots, counterSnapshot{key: key, uplink: st.Uplink, downlink: st.Downlink}) + } + m.statsMu.RUnlock() + + active := make(map[string]struct{}, len(snapshots)) + for _, snapshot := range snapshots { + xrayBandwidth.Observe(snapshot.key, snapshot.uplink, snapshot.downlink, now) + active[snapshot.key] = struct{}{} + } + xrayBandwidth.Retain(active) +} + +// RuntimeRateForKeys resolves a client's live speed. Clients are tracked under +// their UUID in native mode and under their stats-API email in external mode, +// so callers pass every identifier the client may be stored under. +func (m *XrayManager) RuntimeRateForKeys(keys ...string) (bandwidthRate, bool) { + return xrayBandwidth.RateForKeys(keys...) +} + +func (m *XrayManager) isRunningSnapshot() bool { + m.mu.Lock() + native := m.cfg != nil && m.cfg.UseNative() + m.mu.Unlock() + if native { + return nativeXray.nativeRunning() + } + m.mu.Lock() + defer m.mu.Unlock() + return m.isRunning() +} + +func (m *XrayManager) apiCommandConfig() (binPath, apiServer string, ok bool) { + m.mu.Lock() + defer m.mu.Unlock() + if m.cfg == nil || m.cfg.BinPath == "" || m.cfg.ExternalConfigFile() == "" { + return "", "", false + } + binPath = m.cfg.BinPath + apiServer = strings.TrimSpace(m.cfg.APIServer) + if apiServer == "" { + apiServer = m.discoverAPIServerLocked() + } + return binPath, apiServer, apiServer != "" +} + +func (m *XrayManager) discoverAPIServerLocked() string { + if m.cfg == nil || m.cfg.ExternalConfigFile() == "" { + return "" + } + data, err := os.ReadFile(m.cfg.ExternalConfigFile()) + if err != nil { + return "" + } + var cfg struct { + Inbounds []struct { + Tag string `json:"tag"` + Listen string `json:"listen"` + Protocol string `json:"protocol"` + Port json.RawMessage `json:"port"` + } `json:"inbounds"` + } + if err := json.Unmarshal(data, &cfg); err != nil { + return "" + } + for _, ib := range cfg.Inbounds { + if ib.Tag != "api" || !strings.EqualFold(ib.Protocol, "dokodemo-door") { + continue + } + host := strings.TrimSpace(ib.Listen) + if host == "" || host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + port := strings.Trim(string(ib.Port), `"`) + if port == "" || port == "null" { + continue + } + return host + ":" + port + } + return "" +} + +func (m *XrayManager) refreshRuntimeStats() { + if !m.isRunningSnapshot() { + return + } + traffic, err := m.queryUserTraffic() + now := time.Now() + m.statsMu.Lock() + defer m.statsMu.Unlock() + m.lastStatsPoll = now + if err != nil { + m.lastStatsErr = err.Error() + return + } + m.lastStatsErr = "" + if m.statsByEmail == nil { + m.statsByEmail = make(map[string]xrayRuntimeStat, len(traffic)) + } + // External mode: the counters only move once per poll, so this is also the + // natural cadence for the live speed sampler. + active := make(map[string]struct{}, len(traffic)) + for email, counters := range traffic { + active[email] = struct{}{} + xrayBandwidth.Observe(email, counters.Uplink, counters.Downlink, now) + prev := m.statsByEmail[email] + st := xrayRuntimeStat{Email: email, Uplink: counters.Uplink, Downlink: counters.Downlink, LastActive: prev.LastActive, ActiveConnections: prev.ActiveConnections} + changed := counters.Uplink != prev.Uplink || counters.Downlink != prev.Downlink + // First successful poll with non-zero traffic means the client has been + // active since Xray started. Later polls refresh LastActive only when bytes + // move, which avoids counting old idle clients forever. + if changed && (prev.Email != "" || counters.Uplink+counters.Downlink > 0) { + st.LastActive = now + } + m.statsByEmail[email] = st + } + // Keep old stat entries, but do not delete them immediately: Xray may omit + // zero counters for users that have not moved traffic yet. Speed samples are + // dropped for absent users because a missing baseline only costs one poll. + xrayBandwidth.Retain(active) +} + +func (m *XrayManager) refreshRuntimeStatsIfStale(maxAge time.Duration) { + if !m.isRunningSnapshot() { + return + } + m.statsMu.RLock() + last := m.lastStatsPoll + m.statsMu.RUnlock() + if last.IsZero() || time.Since(last) >= maxAge { + m.refreshRuntimeStats() + } +} + +func (m *XrayManager) queryUserTraffic() (map[string]xrayTrafficCounters, error) { + binPath, apiServer, ok := m.apiCommandConfig() + if !ok { + return nil, fmt.Errorf("Xray API stats not configured; add an api inbound or set xray.api_server") + } + attempts := [][]string{ + {"api", "statsquery", "--server=" + apiServer, "-pattern", "user>>>", "-reset=false"}, + {"api", "statsquery", "--server", apiServer, "-pattern", "user>>>", "-reset=false"}, + {"api", "statsquery", "--server=" + apiServer, "-pattern", "user>>>"}, + {"api", "statsquery", "--server", apiServer, "-pattern", "user>>>"}, + } + var lastErr error + for _, args := range attempts { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + cmd := exec.CommandContext(ctx, binPath, args...) + out, err := cmd.CombinedOutput() + cancel() + if err == nil { + return parseXrayStatsOutput(out), nil + } + lastErr = fmt.Errorf("%v: %s", err, strings.TrimSpace(string(out))) + } + return nil, fmt.Errorf("Xray stats query failed: %v", lastErr) +} + +func parseXrayStatsOutput(out []byte) map[string]xrayTrafficCounters { + result := map[string]xrayTrafficCounters{} + type rawStat struct { + Name string `json:"name"` + Value json.RawMessage `json:"value"` + } + var js struct { + Stat []rawStat `json:"stat"` + Stats []rawStat `json:"stats"` + } + if json.Unmarshal(out, &js) == nil { + for _, st := range js.Stat { + addXrayCounter(result, st.Name, parseXrayStatValue(st.Value)) + } + for _, st := range js.Stats { + addXrayCounter(result, st.Name, parseXrayStatValue(st.Value)) + } + } + if len(result) > 0 { + return result + } + + // Text/protobuf form: name: "user>>>..." value: 123 + reText := regexp.MustCompile(`(?s)name:\s*"([^"]+)"\s+value:\s*([0-9]+)`) + for _, m := range reText.FindAllSubmatch(out, -1) { + v, _ := strconv.ParseInt(string(m[2]), 10, 64) + addXrayCounter(result, string(m[1]), v) + } + if len(result) > 0 { + return result + } + + // Some Xray/protobuf JSON builds encode int64 values as strings. + reJSON := regexp.MustCompile(`"name"\s*:\s*"([^"]+)"[^}]*"value"\s*:\s*"?([0-9]+)"?`) + for _, m := range reJSON.FindAllSubmatch(out, -1) { + v, _ := strconv.ParseInt(string(m[2]), 10, 64) + addXrayCounter(result, string(m[1]), v) + } + return result +} + +func parseXrayStatValue(raw json.RawMessage) int64 { + if len(raw) == 0 { + return 0 + } + var n int64 + if err := json.Unmarshal(raw, &n); err == nil { + return n + } + var f float64 + if err := json.Unmarshal(raw, &f); err == nil { + return int64(f) + } + var s string + if err := json.Unmarshal(raw, &s); err == nil { + v, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64) + return v + } + return 0 +} + +func addXrayCounter(result map[string]xrayTrafficCounters, name string, value int64) { + // Xray user traffic stats are normally named: + // user>>>EMAIL>>>traffic>>>uplink + // user>>>EMAIL>>>traffic>>>downlink + // Older code expected a fifth segment and therefore ignored valid Xray + // Stats API responses, which made every client look offline. + parts := strings.Split(name, ">>>") + if len(parts) < 4 || parts[0] != "user" || parts[2] != "traffic" { + return + } + email := strings.TrimSpace(parts[1]) + direction := strings.ToLower(strings.TrimSpace(parts[3])) + if email == "" { + return + } + c := result[email] + switch direction { + case "uplink": + c.Uplink = value + case "downlink": + c.Downlink = value + default: + return + } + result[email] = c +} + +func (m *XrayManager) RuntimeStatsForEmail(email string) (xrayRuntimeStat, bool) { + return m.RuntimeStatsForKeys(email) +} + +func (m *XrayManager) RuntimeStatsForKeys(keys ...string) (xrayRuntimeStat, bool) { + m.statsMu.RLock() + defer m.statsMu.RUnlock() + for _, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + if st, ok := m.statsByEmail[key]; ok && st.Email != "" { + return st, true + } + } + return xrayRuntimeStat{}, false +} + +func (m *XrayManager) CountOnlineUsers() int { + window := m.onlineWindow() + now := time.Now() + m.statsMu.RLock() + defer m.statsMu.RUnlock() + n := 0 + for _, st := range m.statsByEmail { + if st.ActiveConnections > 0 || (!st.LastActive.IsZero() && now.Sub(st.LastActive) <= window) { + n++ + } + } + return n +} + +func (m *XrayManager) activeConfigFileLocked() string { + if m.cfg == nil { + return "" + } + return m.cfg.ActiveConfigFile() +} + +func (m *XrayManager) configStoreKeyLocked() string { + if m.cfg == nil { + return "default" + } + mode := m.cfg.ModeName() + path := strings.TrimSpace(m.activeConfigFileLocked()) + if path == "" { + path = "default" + } + return mode + ":" + path +} + +func normalizeJSONIndent(data []byte) ([]byte, error) { + var raw interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + return json.MarshalIndent(raw, "", " ") +} + +func forceXrayDebugLogBytes(data []byte) ([]byte, bool, error) { + if !json.Valid(data) { + return nil, false, fmt.Errorf("invalid JSON") + } + var raw map[string]interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return nil, false, fmt.Errorf("parse xray config: %w", err) + } + if raw == nil { + return nil, false, fmt.Errorf("xray config must be a JSON object") + } + changed := ensureXrayForcedDebugLogConfig(raw) + if !changed { + return data, false, nil + } + out, err := json.MarshalIndent(raw, "", " ") + if err != nil { + return nil, false, err + } + return out, true, nil +} + +func ensureXrayForcedDebugLogConfig(raw map[string]interface{}) bool { + changed := false + logObj := asObject(raw["log"]) + if logObj == nil { + logObj = map[string]interface{}{} + raw["log"] = logObj + changed = true + } + if v, _ := logObj["access"].(string); v != xrayForcedAccessLogPath { + logObj["access"] = xrayForcedAccessLogPath + changed = true + } + if v, _ := logObj["error"].(string); v != xrayForcedErrorLogPath { + logObj["error"] = xrayForcedErrorLogPath + changed = true + } + if v, _ := logObj["loglevel"].(string); !strings.EqualFold(v, xrayForcedLogLevel) { + logObj["loglevel"] = xrayForcedLogLevel + changed = true + } + if v, _ := logObj["dnsLog"].(bool); !v { + logObj["dnsLog"] = true + changed = true + } + return changed +} + +func (m *XrayManager) readConfigLocked() ([]byte, error) { + configFile := m.activeConfigFileLocked() + if m.cfg == nil || configFile == "" { + return nil, fmt.Errorf("xray config file not configured") + } + if statsStore != nil { + if data, ok, err := statsStore.GetXrayConfig(context.Background(), m.configStoreKeyLocked()); err != nil { + xrayLogf("xray: database config read failed, falling back to file: %v", err) + } else if ok { + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return nil, err + } else if changed { + data = forced + _ = statsStore.UpsertXrayConfig(context.Background(), m.configStoreKeyLocked(), forced) + xrayLogf("xray: forced debug log output in database config") + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + return nil, err + } + _ = writeFileAtomic(configFile, pretty, 0o600) + return pretty, nil + } + } + data, err := os.ReadFile(configFile) + if err != nil { + return nil, err + } + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return nil, err + } else if changed { + data = forced + _ = writeFileAtomic(configFile, forced, 0o600) + xrayLogf("xray: forced debug log output in file config") + } + return data, nil +} + +func (m *XrayManager) writeConfigLocked(data []byte) error { + configFile := m.activeConfigFileLocked() + if m.cfg == nil || configFile == "" { + return fmt.Errorf("xray config file not configured") + } + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return err + } else if changed { + data = forced + xrayLogf("xray: forced debug log output while saving config") + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + return err + } + if statsStore != nil { + if err := statsStore.UpsertXrayConfig(context.Background(), m.configStoreKeyLocked(), pretty); err != nil { + return fmt.Errorf("save Xray config to database: %w", err) + } + } + if err := writeFileAtomic(configFile, pretty, 0o600); err != nil { + return err + } + m.importConfigClientsLocked(pretty, "saved xray config") + return nil +} + +func (m *XrayManager) importConfigClientsLocked(data []byte, source string) { + if statsStore == nil || len(data) == 0 { + return + } + n, err := statsStore.ImportXrayClientsFromConfig(context.Background(), data) + if err != nil { + xrayLogf("xray: import clients from %s failed: %v", source, err) + return + } + if n > 0 { + xrayLogf("xray: imported/synced %d client UUIDs from %s into database", n, source) + } +} + +func (m *XrayManager) importRuntimeConfigFileClientsLocked(source string) { + configFile := m.activeConfigFileLocked() + if m.cfg == nil || strings.TrimSpace(configFile) == "" || statsStore == nil { + return + } + data, err := os.ReadFile(configFile) + if err != nil { + if !os.IsNotExist(err) { + xrayLogf("xray: read %s for client import failed: %v", configFile, err) + } + return + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + xrayLogf("xray: cannot import clients from %s: invalid JSON: %v", configFile, err) + return + } + m.importConfigClientsLocked(pretty, source) +} + +func (m *XrayManager) restartIfExternalRunning() { + m.mu.Lock() + external := m.cfg != nil && !m.cfg.UseNative() + running := external && m.isRunning() + m.mu.Unlock() + if !running { + return + } + if err := m.Restart(); err != nil { + xrayLogf("xray: external restart after client/config change failed: %v", err) + } +} + +func (m *XrayManager) useNativeMode() bool { + m.mu.Lock() + defer m.mu.Unlock() + return m.cfg != nil && m.cfg.UseNative() +} + +func (m *XrayManager) bootstrapConfigStoreLocked() error { + configFile := m.activeConfigFileLocked() + if m.cfg == nil || configFile == "" || statsStore == nil { + return nil + } + ctx := context.Background() + key := m.configStoreKeyLocked() + + if data, ok, err := statsStore.GetXrayConfig(ctx, key); err != nil { + return err + } else if ok { + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return err + } else if changed { + data = forced + if err := statsStore.UpsertXrayConfig(ctx, key, forced); err != nil { + return err + } + xrayLogf("xray: forced debug log output during config bootstrap") + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + return err + } + m.importConfigClientsLocked(pretty, "database xray config") + return writeFileAtomic(configFile, pretty, 0o600) + } + + data, err := os.ReadFile(configFile) + if err != nil { + if os.IsNotExist(err) && m.cfg.UseNative() { + // One-time migration only: if this node already has an old external + // config and no native config exists yet, clone it into the native path. + // After this point native mode reads/writes only its own DB row/file. + if migrated, migErr := m.seedNativeConfigFromExternalLocked(configFile); migErr != nil { + return migErr + } else if len(migrated) > 0 { + if forced, changed, err := forceXrayDebugLogBytes(migrated); err != nil { + return err + } else if changed { + migrated = forced + xrayLogf("xray: forced debug log output during native config migration") + } + pretty, err := normalizeJSONIndent(migrated) + if err != nil { + return err + } + m.importConfigClientsLocked(pretty, "one-time external-to-native migration") + if err := statsStore.UpsertXrayConfig(ctx, key, pretty); err != nil { + return err + } + return writeFileAtomic(configFile, pretty, 0o600) + } + } + if os.IsNotExist(err) { + return nil + } + return err + } + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return err + } else if changed { + data = forced + xrayLogf("xray: forced debug log output while importing runtime config") + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + return err + } + m.importConfigClientsLocked(pretty, "runtime xray config") + return statsStore.UpsertXrayConfig(ctx, key, pretty) +} + +func (m *XrayManager) seedNativeConfigFromExternalLocked(nativeConfigFile string) ([]byte, error) { + if m.cfg == nil || !m.cfg.UseNative() { + return nil, nil + } + ext := strings.TrimSpace(m.cfg.ExternalConfigFile()) + if ext == "" || ext == nativeConfigFile { + return nil, nil + } + data, err := os.ReadFile(ext) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, err + } + if _, err := normalizeJSONIndent(data); err != nil { + return nil, err + } + xrayLogf("xray native: cloned %s to independent native config %s once", ext, nativeConfigFile) + return data, nil +} + +func (m *XrayManager) syncConfigFileFromStoreLocked() error { + configFile := m.activeConfigFileLocked() + if m.cfg == nil || configFile == "" || statsStore == nil { + return nil + } + data, ok, err := statsStore.GetXrayConfig(context.Background(), m.configStoreKeyLocked()) + if err != nil || !ok { + return err + } + if forced, changed, err := forceXrayDebugLogBytes(data); err != nil { + return err + } else if changed { + data = forced + if err := statsStore.UpsertXrayConfig(context.Background(), m.configStoreKeyLocked(), forced); err != nil { + return err + } + xrayLogf("xray: forced debug log output while syncing config") + } + pretty, err := normalizeJSONIndent(data) + if err != nil { + return err + } + m.importConfigClientsLocked(pretty, "database xray config") + return writeFileAtomic(configFile, pretty, 0o600) +} + +// GetConfig reads the current Xray JSON config. With PostgreSQL enabled, the +// database row is canonical and the file is only a synchronized runtime copy. +func (m *XrayManager) GetConfig() ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.readConfigLocked() +} + +// SetConfig validates and writes a new Xray JSON config to DB and to the runtime file. +func (m *XrayManager) SetConfig(data []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + patched, changed, err := patchXrayStatsAPIBytes(data) + if err != nil { + return err + } + if changed { + xrayLogf("xray: added/repaired Stats API support and forced debug logs while saving config") + } + if m.cfg != nil && m.cfg.UseNative() { + if err := validateNativeInboundBindings(patched); err != nil { + return err + } + } + return m.writeConfigLocked(patched) +} + +type xrayStatsConfigCheck struct { + Configured bool + Missing []string + APIServer string +} + +func (m *XrayManager) CheckStatsAPIConfig() (xrayStatsConfigCheck, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.checkStatsAPIConfigLocked() +} + +func (m *XrayManager) checkStatsAPIConfigLocked() (xrayStatsConfigCheck, error) { + data, err := m.readConfigLocked() + if err != nil { + return xrayStatsConfigCheck{}, err + } + var raw map[string]interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return xrayStatsConfigCheck{}, fmt.Errorf("parse xray config: %w", err) + } + if raw == nil { + return xrayStatsConfigCheck{}, fmt.Errorf("xray config must be a JSON object") + } + check := checkXrayStatsAPIConfig(raw) + if check.APIServer == "" { + check.APIServer = m.discoverAPIServerFromRaw(raw) + } + return check, nil +} + +func (m *XrayManager) EnsureStatsAPIConfig() (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.ensureStatsAPIConfigLocked() +} + +func (m *XrayManager) ensureStatsAPIConfigLocked() (bool, error) { + data, err := m.readConfigLocked() + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, err + } + patched, changed, err := patchXrayStatsAPIBytes(data) + if err != nil { + return false, err + } + if !changed { + return false, nil + } + return true, m.writeConfigLocked(patched) +} + +func patchXrayStatsAPIBytes(data []byte) ([]byte, bool, error) { + if !json.Valid(data) { + return nil, false, fmt.Errorf("invalid JSON") + } + var raw map[string]interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return nil, false, fmt.Errorf("parse xray config: %w", err) + } + if raw == nil { + return nil, false, fmt.Errorf("xray config must be a JSON object") + } + changed, _ := ensureXrayStatsAPIConfig(raw) + if ensureXrayForcedDebugLogConfig(raw) { + changed = true + } + if !changed { + return data, false, nil + } + out, err := json.MarshalIndent(raw, "", " ") + if err != nil { + return nil, false, err + } + return out, true, nil +} + +func ensureXrayStatsAPIConfig(raw map[string]interface{}) (bool, xrayStatsConfigCheck) { + changed := false + + api := asObject(raw["api"]) + if api == nil { + api = map[string]interface{}{} + raw["api"] = api + changed = true + } + if tag, _ := api["tag"].(string); tag != "api" { + api["tag"] = "api" + changed = true + } + services, ok := api["services"].([]interface{}) + if !ok { + services = []interface{}{} + } + for _, svc := range []string{"HandlerService", "LoggerService", "StatsService"} { + if !sliceHasString(services, svc) { + services = append(services, svc) + changed = true + } + } + api["services"] = services + + if asObject(raw["stats"]) == nil { + raw["stats"] = map[string]interface{}{} + changed = true + } + + policy := asObject(raw["policy"]) + if policy == nil { + policy = map[string]interface{}{} + raw["policy"] = policy + changed = true + } + levels := asObject(policy["levels"]) + if levels == nil { + levels = map[string]interface{}{} + policy["levels"] = levels + changed = true + } + level0 := asObject(levels["0"]) + if level0 == nil { + level0 = map[string]interface{}{} + levels["0"] = level0 + changed = true + } + for _, key := range []string{"statsUserUplink", "statsUserDownlink"} { + if v, _ := level0[key].(bool); !v { + level0[key] = true + changed = true + } + } + system := asObject(policy["system"]) + if system == nil { + system = map[string]interface{}{} + policy["system"] = system + changed = true + } + for _, key := range []string{"statsInboundUplink", "statsInboundDownlink"} { + if v, _ := system[key].(bool); !v { + system[key] = true + changed = true + } + } + + inbounds, _ := raw["inbounds"].([]interface{}) + apiInbound := findObjectByTag(inbounds, "api") + if apiInbound == nil { + apiInbound = map[string]interface{}{ + "tag": "api", + "listen": "127.0.0.1", + "port": float64(10085), + "protocol": "dokodemo-door", + "settings": map[string]interface{}{"address": "127.0.0.1"}, + } + inbounds = append([]interface{}{apiInbound}, inbounds...) + raw["inbounds"] = inbounds + changed = true + } else { + if proto, _ := apiInbound["protocol"].(string); !strings.EqualFold(proto, "dokodemo-door") { + apiInbound["protocol"] = "dokodemo-door" + changed = true + } + if strings.TrimSpace(fmt.Sprint(apiInbound["listen"])) == "" { + apiInbound["listen"] = "127.0.0.1" + changed = true + } + if _, ok := apiInbound["port"]; !ok || strings.TrimSpace(fmt.Sprint(apiInbound["port"])) == "" || strings.TrimSpace(fmt.Sprint(apiInbound["port"])) == "" { + apiInbound["port"] = float64(10085) + changed = true + } + settings := asObject(apiInbound["settings"]) + if settings == nil { + settings = map[string]interface{}{} + apiInbound["settings"] = settings + changed = true + } + if strings.TrimSpace(fmt.Sprint(settings["address"])) == "" || strings.TrimSpace(fmt.Sprint(settings["address"])) == "" { + settings["address"] = "127.0.0.1" + changed = true + } + } + + outbounds, _ := raw["outbounds"].([]interface{}) + if findObjectByTag(outbounds, "api") == nil { + outbounds = append(outbounds, map[string]interface{}{"tag": "api", "protocol": "freedom", "settings": map[string]interface{}{}}) + raw["outbounds"] = outbounds + changed = true + } + + routing := asObject(raw["routing"]) + if routing == nil { + routing = map[string]interface{}{} + raw["routing"] = routing + changed = true + } + rules, _ := routing["rules"].([]interface{}) + if !hasAPIRoutingRule(rules) { + rules = append([]interface{}{map[string]interface{}{"type": "field", "inboundTag": []interface{}{"api"}, "outboundTag": "api"}}, rules...) + routing["rules"] = rules + changed = true + } + + if ensureXrayClientEmails(raw) { + changed = true + } + + return changed, checkXrayStatsAPIConfig(raw) +} + +func checkXrayStatsAPIConfig(raw map[string]interface{}) xrayStatsConfigCheck { + missing := []string{} + api := asObject(raw["api"]) + if api == nil { + missing = append(missing, "api.services") + } else { + services, _ := api["services"].([]interface{}) + if !sliceHasString(services, "StatsService") { + missing = append(missing, "api.services StatsService") + } + } + if asObject(raw["stats"]) == nil { + missing = append(missing, "stats") + } + policy := asObject(raw["policy"]) + levels := asObject(nil) + level0 := asObject(nil) + if policy != nil { + levels = asObject(policy["levels"]) + if levels != nil { + level0 = asObject(levels["0"]) + } + } + if level0 == nil { + missing = append(missing, "policy.levels.0") + } else { + if v, _ := level0["statsUserUplink"].(bool); !v { + missing = append(missing, "policy.levels.0.statsUserUplink") + } + if v, _ := level0["statsUserDownlink"].(bool); !v { + missing = append(missing, "policy.levels.0.statsUserDownlink") + } + } + + inbounds, _ := raw["inbounds"].([]interface{}) + apiInbound := findObjectByTag(inbounds, "api") + if apiInbound == nil { + missing = append(missing, "api inbound") + } + outbounds, _ := raw["outbounds"].([]interface{}) + if findObjectByTag(outbounds, "api") == nil { + missing = append(missing, "api outbound") + } + if n := countXrayClientEmailIssues(raw); n > 0 { + missing = append(missing, fmt.Sprintf("%d client stats labels", n)) + } + routing := asObject(raw["routing"]) + if routing == nil { + missing = append(missing, "routing api rule") + } else { + rules, _ := routing["rules"].([]interface{}) + if !hasAPIRoutingRule(rules) { + missing = append(missing, "routing api rule") + } + } + return xrayStatsConfigCheck{Configured: len(missing) == 0, Missing: missing, APIServer: discoverAPIServerFromRaw(raw)} +} + +func (m *XrayManager) discoverAPIServerFromRaw(raw map[string]interface{}) string { + return discoverAPIServerFromRaw(raw) +} + +func discoverAPIServerFromRaw(raw map[string]interface{}) string { + inbounds, _ := raw["inbounds"].([]interface{}) + for _, item := range inbounds { + ib, ok := item.(map[string]interface{}) + if !ok { + continue + } + tag, _ := ib["tag"].(string) + proto, _ := ib["protocol"].(string) + if tag != "api" || !strings.EqualFold(proto, "dokodemo-door") { + continue + } + host, _ := ib["listen"].(string) + host = strings.TrimSpace(host) + if host == "" || host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + port := strings.TrimSpace(fmt.Sprint(ib["port"])) + port = strings.Trim(port, `"`) + if port == "" || port == "" || port == "null" { + continue + } + return host + ":" + port + } + return "" +} + +func countXrayClientEmailIssues(raw map[string]interface{}) int { + inbounds, _ := raw["inbounds"].([]interface{}) + seen := map[string]int{} + issues := 0 + for _, ib := range inbounds { + ibMap, ok := ib.(map[string]interface{}) + if !ok { + continue + } + proto, _ := ibMap["protocol"].(string) + if !xrayClientProtos[strings.ToLower(proto)] { + continue + } + settings, _ := ibMap["settings"].(map[string]interface{}) + if settings == nil { + continue + } + clients, _ := settings["clients"].([]interface{}) + for _, item := range clients { + cm, ok := item.(map[string]interface{}) + if !ok { + continue + } + email := safeXrayStatsEmail(firstNonEmptyString(cm["email"])) + if email == "" || seen[email] > 0 { + issues++ + } + if email != "" { + seen[email]++ + } + } + } + return issues +} + +func ensureXrayClientEmails(raw map[string]interface{}) bool { + changed := false + inbounds, _ := raw["inbounds"].([]interface{}) + seen := map[string]int{} + for _, ib := range inbounds { + ibMap, ok := ib.(map[string]interface{}) + if !ok { + continue + } + proto, _ := ibMap["protocol"].(string) + if !xrayClientProtos[strings.ToLower(proto)] { + continue + } + settings, _ := ibMap["settings"].(map[string]interface{}) + if settings == nil { + continue + } + clients, _ := settings["clients"].([]interface{}) + for idx, item := range clients { + cm, ok := item.(map[string]interface{}) + if !ok { + continue + } + email := safeXrayStatsEmail(firstNonEmptyString(cm["email"])) + if email == "" || seen[email] > 0 { + base := firstNonEmptyString(cm["name"], cm["email"], cm["id"], cm["password"]) + if base == "" { + base = fmt.Sprintf("client-%d", idx+1) + } + email = uniqueXrayEmail(base, seen) + cm["email"] = email + changed = true + } + if _, ok := cm["level"]; !ok { + cm["level"] = float64(0) + changed = true + } + seen[email]++ + } + } + return changed +} + +func firstNonEmptyString(values ...interface{}) string { + for _, v := range values { + s := strings.TrimSpace(fmt.Sprint(v)) + if s != "" && s != "" { + return s + } + } + return "" +} + +func uniqueXrayEmail(base string, seen map[string]int) string { + email := safeXrayStatsEmail(base) + if email == "" { + email = "xray-client" + } + if len(email) > 40 { + email = email[:40] + email = strings.Trim(email, "-_.") + if email == "" { + email = "xray-client" + } + } + candidate := email + for i := 2; seen[candidate] > 0; i++ { + candidate = fmt.Sprintf("%s-%d", email, i) + } + return candidate +} + +func safeXrayStatsEmail(s string) string { + s = strings.TrimSpace(s) + if s == "" || s == "" { + return "" + } + var b strings.Builder + lastDash := false + for _, r := range s { + ok := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '@' || r == '.' || r == '_' || r == '-' + if ok { + b.WriteRune(r) + lastDash = false + } else if !lastDash { + b.WriteByte('-') + lastDash = true + } + } + return strings.Trim(b.String(), "-_.") +} + +func asObject(v interface{}) map[string]interface{} { + m, _ := v.(map[string]interface{}) + return m +} + +func findObjectByTag(items []interface{}, tag string) map[string]interface{} { + for _, item := range items { + m, ok := item.(map[string]interface{}) + if !ok { + continue + } + if t, _ := m["tag"].(string); t == tag { + return m + } + } + return nil +} + +func sliceHasString(items []interface{}, want string) bool { + for _, item := range items { + if s, ok := item.(string); ok && strings.EqualFold(s, want) { + return true + } + } + return false +} + +func hasAPIRoutingRule(rules []interface{}) bool { + for _, item := range rules { + rule, ok := item.(map[string]interface{}) + if !ok { + continue + } + outbound, _ := rule["outboundTag"].(string) + if outbound != "api" { + continue + } + tags, ok := rule["inboundTag"].([]interface{}) + if !ok { + if tag, _ := rule["inboundTag"].(string); tag == "api" { + return true + } + continue + } + if sliceHasString(tags, "api") { + return true + } + } + return false +} + +// ---- Admin HTTP handlers ---- + +func handleXrayStatus(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/status", nil, "") { + return + } + // Be practical for old/manual configs: if the panel detects missing Stats API + // pieces or missing per-client stat labels, repair once automatically. This + // avoids a dashboard that says "OK" but continues to show zero Xray online + // users until a technical admin manually edits JSON. + if !xrayMgr.useNativeMode() { + if check, err := xrayMgr.CheckStatsAPIConfig(); err == nil && !check.Configured { + wasRunning := xrayMgr.isRunningSnapshot() + if changed, err := xrayMgr.EnsureStatsAPIConfig(); err == nil && changed && wasRunning { + if err := xrayMgr.Restart(); err != nil { + xrayLogf("xray: auto stats repair restart failed: %v", err) + } + } + } + } + status := xrayMgr.Status() + if sess := sessionFromCtx(r.Context()); sess != nil && sess.Role == RoleReseller && statsStore != nil { + metas, err := statsStore.ListXrayClientsByOwner(r.Context(), sess.Username) + if err == nil { + status.OnlineUsers = 0 + window := xrayMgr.onlineWindow() + now := time.Now() + for _, m := range metas { + online := m.ActiveConnections > 0 || (m.LastActive != nil && now.Sub(*m.LastActive) <= window) + if st, ok := xrayMgr.RuntimeStatsForKeys(m.Email, m.UUID, m.Name); ok { + online = online || st.ActiveConnections > 0 || (!st.LastActive.IsZero() && now.Sub(st.LastActive) <= window) + } + if online { + status.OnlineUsers++ + } + } + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(status) +} + +func handleXrayStart(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/start", nil, "") { + return + } + if err := xrayMgr.Start(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func handleXrayStop(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/stop", nil, "") { + return + } + if err := xrayMgr.Stop(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func handleXrayRestart(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/restart", nil, "") { + return + } + if err := xrayMgr.Restart(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func handleXrayConfig(w http.ResponseWriter, r *http.Request) { + if requestedServerID(r) != "" && requestedServerID(r) != "local" && requestedServerID(r) != "0" { + body := []byte(nil) + if r.Method == http.MethodPost { + var err error + body, err = io.ReadAll(io.LimitReader(r.Body, 512*1024)) + if err != nil { + http.Error(w, "failed to read body", http.StatusBadRequest) + return + } + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/config", body, "") { + return + } + } + switch r.Method { + case http.MethodGet: + data, err := xrayMgr.GetConfig() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(data) + + case http.MethodPost: + body, err := io.ReadAll(io.LimitReader(r.Body, 512*1024)) + if err != nil { + http.Error(w, "failed to read body", http.StatusBadRequest) + return + } + if err := xrayMgr.SetConfig(body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusOK) + + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func handleXrayRepairStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/stats/repair", nil, "") { + return + } + wasRunning := xrayMgr.isRunningSnapshot() + changed, err := xrayMgr.EnsureStatsAPIConfig() + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + restarted := false + if wasRunning { + if err := xrayMgr.Restart(); err != nil { + http.Error(w, "config repaired but restart failed: "+err.Error(), http.StatusInternalServerError) + return + } + restarted = true + } + check, _ := xrayMgr.CheckStatsAPIConfig() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "changed": changed, + "restarted": restarted, + "stats_configured": check.Configured, + "stats_missing": check.Missing, + "api_server": check.APIServer, + }) +} + +func handleXrayLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/logs", nil, "") { + return + } + lines := xrayLogBuf.snapshot() + if lines == nil { + lines = []string{} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{"lines": lines}) +} + +// ---- Inbound / client management ---- + +// XrayClientInfo is a single client entry inside an Xray inbound. +type XrayClientInfo struct { + UUID string `json:"id"` + Password string `json:"password,omitempty"` + Email string `json:"email"` + Level int `json:"level,omitempty"` + // Runtime counters from the Xray stats API. Online means this user's + // traffic counters changed inside the configured online window. + Online bool `json:"online"` + LastActive *time.Time `json:"last_active,omitempty"` + UplinkBytes int64 `json:"uplink_bytes,omitempty"` + DownlinkBytes int64 `json:"downlink_bytes,omitempty"` + TotalBytes int64 `json:"total_bytes,omitempty"` + ActiveConnections int `json:"active_connections,omitempty"` + // Live speed in bytes per second for the whole client, summed across every + // connection it has open. + UpBytesPerSec float64 `json:"up_bytes_per_sec"` + DownBytesPerSec float64 `json:"down_bytes_per_sec"` + // Metadata from PostgreSQL (enriched by handleXrayInbounds) + Name string `json:"name,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + ExpirationDays int `json:"expiration_days"` + MaxConns int `json:"max_conns"` + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + QuotaExceeded bool `json:"quota_exceeded,omitempty"` + OwnerUsername string `json:"owner_username,omitempty"` + Expired bool `json:"expired,omitempty"` +} + +// XrayInboundInfo is returned by /api/xray/inbounds. +type XrayInboundInfo struct { + Tag string `json:"tag"` + Protocol string `json:"protocol"` + Port json.RawMessage `json:"port,omitempty"` + Listen string `json:"listen,omitempty"` + Network string `json:"network,omitempty"` + Path string `json:"path,omitempty"` + SharedPort bool `json:"shared_port,omitempty"` + Clients []XrayClientInfo `json:"clients"` +} + +// protocols that carry a "clients" array in their settings +var xrayClientProtos = map[string]bool{ + "vless": true, "vmess": true, "trojan": true, +} + +// ListInbounds parses the config and returns only inbounds that support client lists. +func (m *XrayManager) ListInbounds() ([]XrayInboundInfo, error) { + m.mu.Lock() + defer m.mu.Unlock() + data, err := m.readConfigLocked() + if err != nil { + return nil, err + } + var cfg struct { + Inbounds []json.RawMessage `json:"inbounds"` + } + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("parse xray config: %w", err) + } + var result []XrayInboundInfo + for _, raw := range cfg.Inbounds { + var ib struct { + Tag string `json:"tag"` + Protocol string `json:"protocol"` + Port json.RawMessage `json:"port"` + Listen string `json:"listen"` + SharedPort bool `json:"dragoncoreSharedPort"` + StreamSettings struct { + Network string `json:"network"` + WSSettings struct { Path string `json:"path"` } `json:"wsSettings"` + XHTTPSettings struct { Path string `json:"path"` } `json:"xhttpSettings"` + SplitHTTPSettings struct { Path string `json:"path"` } `json:"splithttpSettings"` + } `json:"streamSettings"` + Settings struct { + Clients []XrayClientInfo `json:"clients"` + } `json:"settings"` + } + if err := json.Unmarshal(raw, &ib); err != nil { + continue + } + if !xrayClientProtos[strings.ToLower(ib.Protocol)] { + continue + } + clients := ib.Settings.Clients + if clients == nil { + clients = []XrayClientInfo{} + } + for i := range clients { + if clients[i].UUID == "" && clients[i].Password != "" { + clients[i].UUID = clients[i].Password + } + } + result = append(result, XrayInboundInfo{ + Tag: ib.Tag, + Protocol: strings.ToLower(ib.Protocol), + Port: ib.Port, + Listen: ib.Listen, + Network: ib.StreamSettings.Network, + Path: firstNonEmpty(ib.StreamSettings.WSSettings.Path, ib.StreamSettings.XHTTPSettings.Path, ib.StreamSettings.SplitHTTPSettings.Path), + SharedPort: ib.SharedPort, + Clients: clients, + }) + } + if result == nil { + result = []XrayInboundInfo{} + } + return result, nil +} + +// modifyRawConfig reads the config as a generic map, calls fn to mutate it, then writes it back. +// Caller must hold m.mu. +func (m *XrayManager) modifyRawConfig(fn func(cfg map[string]interface{}) error) error { + data, err := m.readConfigLocked() + if err != nil { + return err + } + var raw map[string]interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return fmt.Errorf("parse xray config: %w", err) + } + if raw == nil { + return fmt.Errorf("xray config must be a JSON object") + } + if err := fn(raw); err != nil { + return err + } + out, err := json.MarshalIndent(raw, "", " ") + if err != nil { + return err + } + return m.writeConfigLocked(out) +} + +// AddXrayClient adds a client to the named inbound and saves the config. +func (m *XrayManager) AddXrayClient(inboundTag, uuid, email string) error { + return m.addXrayClient(inboundTag, uuid, email, false) +} + +// EnsureXrayClient restores a previously suspended DB-backed client without +// failing if it is already present in the active config. +func (m *XrayManager) EnsureXrayClient(inboundTag, uuid, email string) error { + return m.addXrayClient(inboundTag, uuid, email, true) +} + +func (m *XrayManager) addXrayClient(inboundTag, uuid, email string, allowExisting bool) error { + m.mu.Lock() + defer m.mu.Unlock() + err := m.modifyRawConfig(func(raw map[string]interface{}) error { + _, _ = ensureXrayStatsAPIConfig(raw) + inbounds, _ := raw["inbounds"].([]interface{}) + for _, ib := range inbounds { + ibMap, ok := ib.(map[string]interface{}) + if !ok { + continue + } + if tag, _ := ibMap["tag"].(string); tag != inboundTag { + continue + } + settings, _ := ibMap["settings"].(map[string]interface{}) + if settings == nil { + settings = make(map[string]interface{}) + ibMap["settings"] = settings + } + clients, _ := settings["clients"].([]interface{}) + for _, c := range clients { + if cm, ok := c.(map[string]interface{}); ok { + id, _ := cm["id"].(string) + if id == "" { + id, _ = cm["password"].(string) + } + if id == uuid { + if allowExisting { + cm["email"] = email + return nil + } + return fmt.Errorf("UUID %s already exists in inbound %s", uuid, inboundTag) + } + } + } + proto, _ := ibMap["protocol"].(string) + client := map[string]interface{}{ + "id": uuid, "email": email, "level": 0, + } + if strings.EqualFold(proto, "vmess") { + client["alterId"] = 0 + } + settings["clients"] = append(clients, client) + return nil + } + return fmt.Errorf("inbound %q not found", inboundTag) + }) + if err == nil && m.cfg != nil && m.cfg.UseNative() { + if hotErr := nativeXray.addClient(inboundTag, uuid, email); hotErr != nil { + xrayLogf("native xray: hot-add client %s to %s failed: %v", uuid, inboundTag, hotErr) + } + } + return err +} + +// RemoveXrayClient removes a client by UUID from the named inbound and saves the config. +func (m *XrayManager) RemoveXrayClient(inboundTag, uuid string) error { + m.mu.Lock() + defer m.mu.Unlock() + err := m.modifyRawConfig(func(raw map[string]interface{}) error { + inbounds, _ := raw["inbounds"].([]interface{}) + for _, ib := range inbounds { + ibMap, ok := ib.(map[string]interface{}) + if !ok { + continue + } + if tag, _ := ibMap["tag"].(string); tag != inboundTag { + continue + } + settings, _ := ibMap["settings"].(map[string]interface{}) + if settings == nil { + return fmt.Errorf("inbound %s has no settings", inboundTag) + } + clients, _ := settings["clients"].([]interface{}) + var kept []interface{} + removed := false + for _, c := range clients { + if cm, ok := c.(map[string]interface{}); ok { + id, _ := cm["id"].(string) + if id == "" { + id, _ = cm["password"].(string) + } + if id == uuid { + removed = true + continue + } + } + kept = append(kept, c) + } + if !removed { + // DB-backed native users may exist only in xray_clients. The inbound + // exists, so let the caller delete the database row too. + return nil + } + settings["clients"] = kept + return nil + } + return fmt.Errorf("inbound %q not found", inboundTag) + }) + if err == nil && m.cfg != nil && m.cfg.UseNative() { + if hotErr := nativeXray.removeClient(inboundTag, uuid); hotErr != nil { + xrayLogf("native xray: hot-remove client %s from %s failed: %v", uuid, inboundTag, hotErr) + } + } + return err +} + +// UpdateXrayClientEmail updates the client's email/stats label inside the Xray JSON config. +// UUID remains immutable; metadata such as display name/expiry stays in PostgreSQL. +func (m *XrayManager) UpdateXrayClientEmail(uuid, email string) error { + if strings.TrimSpace(uuid) == "" || strings.TrimSpace(email) == "" { + return nil + } + m.mu.Lock() + defer m.mu.Unlock() + err := m.modifyRawConfig(func(raw map[string]interface{}) error { + changed := false + inbounds, _ := raw["inbounds"].([]interface{}) + for _, ib := range inbounds { + ibMap, ok := ib.(map[string]interface{}) + if !ok { + continue + } + settings, _ := ibMap["settings"].(map[string]interface{}) + clients, _ := settings["clients"].([]interface{}) + for _, c := range clients { + cm, ok := c.(map[string]interface{}) + if !ok { + continue + } + id, _ := cm["id"].(string) + if id == "" { + id, _ = cm["password"].(string) + } + if id == uuid { + cm["email"] = email + changed = true + } + } + } + if !changed { + return nil + } + return nil + }) + if err == nil && m.cfg != nil && m.cfg.UseNative() { + if hotErr := nativeXray.updateClientEmail(uuid, email); hotErr != nil { + xrayLogf("native xray: hot-update client %s email failed: %v", uuid, hotErr) + } + } + return err +} + +// ---- HTTP handlers for inbound/client management ---- + +func handleXrayInbounds(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + filterOwner := "" + if sess := sessionFromCtx(r.Context()); sess != nil && sess.Role == RoleReseller { + filterOwner = sess.Username + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/xray/inbounds", nil, filterOwner) { + return + } + inbounds, err := xrayMgr.ListInbounds() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + sess := sessionFromCtx(r.Context()) + isReseller := sess != nil && sess.Role == RoleReseller + + // Enrich clients with metadata from PostgreSQL when available. Resellers only + // see their own Xray clients, but they still see all available inbounds so + // they know where they can create new users. + if statsStore != nil { + metas, err := statsStore.ListAllXrayClients(r.Context()) + if err != nil { + if isReseller { + for i := range inbounds { + inbounds[i].Clients = []XrayClientInfo{} + } + } else { + for i := range inbounds { + for j := range inbounds[i].Clients { + applyXrayRuntimeStats(&inbounds[i].Clients[j]) + } + } + } + } else { + metaMap := make(map[string]*XrayClientMeta, len(metas)) + metasByInbound := make(map[string][]*XrayClientMeta) + for _, m := range metas { + metaMap[m.UUID] = m + metasByInbound[m.InboundTag] = append(metasByInbound[m.InboundTag], m) + } + now := time.Now() + for i := range inbounds { + seen := make(map[string]bool) + filtered := make([]XrayClientInfo, 0, len(inbounds[i].Clients)+len(metasByInbound[inbounds[i].Tag])) + appendMetaClient := func(m *XrayClientMeta) { + if m == nil || m.UUID == "" || seen[m.UUID] { + return + } + c := XrayClientInfo{ + UUID: m.UUID, + Email: m.Email, + Name: m.Name, + ExpiresAt: m.ExpiresAt, + MaxConns: m.MaxConns, + DataQuotaBytes: m.DataQuotaBytes, + QuotaAction: normalizeQuotaAction(m.QuotaAction), + QuotaThrottleMbps: quotaThrottleMbpsOrDefault(m.QuotaThrottleMbps), + QuotaExceeded: m.DataQuotaBytes > 0 && m.TotalUplinkBytes+m.TotalDownlinkBytes >= m.DataQuotaBytes, + OwnerUsername: m.OwnerUsername, + UplinkBytes: m.TotalUplinkBytes, + DownlinkBytes: m.TotalDownlinkBytes, + TotalBytes: m.TotalUplinkBytes + m.TotalDownlinkBytes, + LastActive: m.LastActive, + ActiveConnections: m.ActiveConnections, + } + if c.Email == "" { + c.Email = m.UUID + } + if c.ActiveConnections > 0 { + c.Online = true + } else if c.LastActive != nil && now.Sub(*c.LastActive) <= xrayMgr.onlineWindow() { + c.Online = true + } + applyXrayRuntimeStats(&c) + if m.ExpiresAt == nil { + c.ExpirationDays = -1 + } else if m.ExpiresAt.Before(now) { + c.Expired = true + c.ExpirationDays = 0 + } else { + c.ExpirationDays = int(m.ExpiresAt.Sub(now).Hours() / 24) + } + seen[m.UUID] = true + filtered = append(filtered, c) + } + for j := range inbounds[i].Clients { + c := inbounds[i].Clients[j] + applyXrayRuntimeStats(&c) + m, ok := metaMap[c.UUID] + if isReseller && (!ok || m.OwnerUsername != sess.Username) { + continue + } + if !ok { + c.ExpirationDays = -1 + seen[c.UUID] = true + filtered = append(filtered, c) + continue + } + appendMetaClient(m) + } + for _, m := range metasByInbound[inbounds[i].Tag] { + if isReseller && m.OwnerUsername != sess.Username { + continue + } + appendMetaClient(m) + } + inbounds[i].Clients = filtered + } + } + } else if isReseller { + for i := range inbounds { + inbounds[i].Clients = []XrayClientInfo{} + } + } else { + for i := range inbounds { + for j := range inbounds[i].Clients { + applyXrayRuntimeStats(&inbounds[i].Clients[j]) + } + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(inbounds) +} + +func applyXrayRuntimeStats(c *XrayClientInfo) { + if c == nil { + return + } + if rate, ok := xrayMgr.RuntimeRateForKeys(c.Email, c.UUID, c.Name); ok { + c.UpBytesPerSec = rate.UpBytesPerSec + c.DownBytesPerSec = rate.DownBytesPerSec + } + st, ok := xrayMgr.RuntimeStatsForKeys(c.Email, c.UUID, c.Name) + if !ok { + return + } + window := xrayMgr.onlineWindow() + now := time.Now() + if st.Uplink > c.UplinkBytes { + c.UplinkBytes = st.Uplink + } + if st.Downlink > c.DownlinkBytes { + c.DownlinkBytes = st.Downlink + } + c.TotalBytes = c.UplinkBytes + c.DownlinkBytes + c.QuotaExceeded = c.DataQuotaBytes > 0 && c.TotalBytes >= c.DataQuotaBytes + if st.ActiveConnections > c.ActiveConnections { + c.ActiveConnections = st.ActiveConnections + } + if !st.LastActive.IsZero() { + t := st.LastActive + c.LastActive = &t + } + c.Online = c.ActiveConnections > 0 || (c.LastActive != nil && now.Sub(*c.LastActive) <= window) +} + +func handleXrayClientAdd(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + InboundTag string `json:"inbound_tag"` + UUID string `json:"uuid"` + Email string `json:"email"` + Name string `json:"name"` + ExpiresAt string `json:"expires_at"` // RFC3339 or YYYY-MM-DD or empty + MaxConnections int `json:"max_connections"` + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + OwnerUsername string `json:"owner_username,omitempty"` + ServerID string `json:"server_id,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if req.InboundTag == "" || req.UUID == "" { + http.Error(w, "inbound_tag and uuid required", http.StatusBadRequest) + return + } + req.InboundTag = strings.TrimSpace(req.InboundTag) + req.UUID = strings.TrimSpace(req.UUID) + if _, err := parseUUID(req.UUID); err != nil { + http.Error(w, "invalid uuid: "+err.Error(), http.StatusBadRequest) + return + } + if req.MaxConnections < 0 || req.MaxConnections > 10000 { + http.Error(w, "max_connections must be between 0 and 10000", http.StatusBadRequest) + return + } + if err := validateQuotaConfig(req.DataQuotaBytes, req.QuotaAction, req.QuotaThrottleMbps); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if ms, remote, err := managedServerFromID(r.Context(), statsStore, req.ServerID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if !ms.EnableXray { + http.Error(w, "Xray creation is disabled for this server", http.StatusForbidden) + return + } + if sess := sessionFromCtx(r.Context()); sess != nil && sess.Role == RoleReseller { + _, exists, ownerErr := remoteXrayClientOwner(r.Context(), ms, req.UUID) + if ownerErr != nil { + http.Error(w, "could not verify remote ownership", http.StatusBadGateway) + return + } + if exists { + http.Error(w, "UUID already exists", http.StatusConflict) + return + } + owner, ok := adminUsers.get(sess.Username) + used, quotaErr := countOwnedQuotaAcrossManagedServers(r.Context(), statsStore, sess.Username) + if quotaErr != nil { + http.Error(w, "could not verify reseller quota", http.StatusBadGateway) + return + } + if ok && owner.MaxUsers > 0 && used >= owner.MaxUsers { + http.Error(w, fmt.Sprintf("user limit reached (%d)", owner.MaxUsers), http.StatusForbidden) + return + } + req.OwnerUsername = sess.Username + } + req.ServerID = "" + body, _ := json.Marshal(req) + status, data, ct, err := proxyManagedServer(r.Context(), ms, http.MethodPost, "/api/xray/clients/add", body, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + req.Email = strings.TrimSpace(req.Email) + if req.Email == "" { + req.Email = strings.TrimSpace(req.Name) + } + if req.Email == "" { + req.Email = req.UUID + } + expiresAt, err := parseOptionalXrayExpiry(req.ExpiresAt) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + sess := sessionFromCtx(r.Context()) + ownerUsername := "" + if sess != nil && sess.Role == RoleReseller { + ownerUsername = sess.Username + if statsStore == nil { + http.Error(w, "storage not available", http.StatusInternalServerError) + return + } + owner, ok := adminUsers.get(sess.Username) + if !ok || !owner.IsActive || (owner.ExpiresAt != nil && time.Now().After(*owner.ExpiresAt)) { + http.Error(w, "reseller account suspended or expired", http.StatusForbidden) + return + } + used, quotaErr := countOwnedQuotaAcrossManagedServers(r.Context(), statsStore, sess.Username) + if quotaErr != nil { + http.Error(w, "could not verify reseller quota", http.StatusBadGateway) + return + } + if owner.MaxUsers > 0 && used >= owner.MaxUsers { + http.Error(w, fmt.Sprintf("user limit reached (%d)", owner.MaxUsers), http.StatusForbidden) + return + } + } else if sess != nil && sess.Role == RoleSuperAdmin && strings.TrimSpace(req.OwnerUsername) != "" { + ownerUsername = strings.TrimSpace(req.OwnerUsername) + } + + if statsStore != nil { + if _, err := statsStore.GetXrayClientMeta(r.Context(), req.UUID); err == nil { + http.Error(w, "UUID already exists in database", http.StatusBadRequest) + return + } else if err != sql.ErrNoRows { + http.Error(w, "database error: "+err.Error(), http.StatusInternalServerError) + return + } + } + var savedMeta *XrayClientMeta + if statsStore != nil { + meta := XrayClientMeta{ + UUID: req.UUID, + Name: req.Name, + Email: req.Email, + InboundTag: req.InboundTag, + OwnerUsername: ownerUsername, + MaxConns: req.MaxConnections, + DataQuotaBytes: req.DataQuotaBytes, + QuotaAction: normalizeQuotaAction(req.QuotaAction), + QuotaThrottleMbps: quotaThrottleMbpsOrDefault(req.QuotaThrottleMbps), + } + meta.ExpiresAt = expiresAt + if err := statsStore.UpsertXrayClientMeta(r.Context(), meta); err != nil { + http.Error(w, "save client metadata failed: "+err.Error(), http.StatusInternalServerError) + return + } + xrayMgr.setNativeQuotaPolicy(&meta) + savedMeta = &meta + } + // Publish the credential only after its quota/owner/expiry policy exists, so + // a fast native client can never enter an unmetered window during creation. + if err := xrayMgr.AddXrayClient(req.InboundTag, req.UUID, req.Email); err != nil { + if savedMeta != nil { + _ = statsStore.DeleteXrayClientMeta(r.Context(), req.UUID) + } + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + xrayMgr.restartIfExternalRunning() + w.WriteHeader(http.StatusCreated) +} + +// handleXrayClientUpdate updates DB metadata and mirrors the email/stats label +// into the Xray JSON config when the client also exists there. +func handleXrayClientUpdate(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + UUID string `json:"uuid"` + Name string `json:"name"` + Email string `json:"email"` + ExpiresAt string `json:"expires_at"` + MaxConnections int `json:"max_connections"` + DataQuotaBytes int64 `json:"data_quota_bytes"` + QuotaAction string `json:"quota_action"` + QuotaThrottleMbps int `json:"quota_throttle_mbps"` + ResetUsage bool `json:"reset_usage,omitempty"` + ServerID string `json:"server_id,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + if req.UUID == "" { + http.Error(w, "uuid required", http.StatusBadRequest) + return + } + req.UUID = strings.TrimSpace(req.UUID) + if _, err := parseUUID(req.UUID); err != nil { + http.Error(w, "invalid uuid: "+err.Error(), http.StatusBadRequest) + return + } + if req.MaxConnections < 0 || req.MaxConnections > 10000 { + http.Error(w, "max_connections must be between 0 and 10000", http.StatusBadRequest) + return + } + if err := validateQuotaConfig(req.DataQuotaBytes, req.QuotaAction, req.QuotaThrottleMbps); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if ms, remote, err := managedServerFromID(r.Context(), statsStore, req.ServerID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if sess := sessionFromCtx(r.Context()); sess != nil && sess.Role == RoleReseller && !remoteXrayClientOwned(r.Context(), ms, req.UUID, sess.Username) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + req.ServerID = "" + body, _ := json.Marshal(req) + status, data, ct, err := proxyManagedServer(r.Context(), ms, http.MethodPost, "/api/xray/clients/update", body, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + if statsStore == nil { + http.Error(w, "storage not available", http.StatusInternalServerError) + return + } + + existing, err := statsStore.GetXrayClientMeta(r.Context(), req.UUID) + if err != nil { + http.Error(w, "client metadata not found", http.StatusNotFound) + return + } + sess := sessionFromCtx(r.Context()) + if sess != nil && sess.Role == RoleReseller && existing.OwnerUsername != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + req.Email = strings.TrimSpace(req.Email) + if req.Email == "" { + req.Email = firstNonEmpty(strings.TrimSpace(req.Name), existing.Email, req.UUID) + } + expiresAt, err := parseOptionalXrayExpiry(req.ExpiresAt) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + meta := XrayClientMeta{ + UUID: req.UUID, + Name: req.Name, + Email: req.Email, + InboundTag: existing.InboundTag, + OwnerUsername: existing.OwnerUsername, + MaxConns: req.MaxConnections, + DataQuotaBytes: req.DataQuotaBytes, + QuotaAction: normalizeQuotaAction(req.QuotaAction), + QuotaThrottleMbps: quotaThrottleMbpsOrDefault(req.QuotaThrottleMbps), + TotalUplinkBytes: existing.TotalUplinkBytes, + TotalDownlinkBytes: existing.TotalDownlinkBytes, + } + meta.ExpiresAt = expiresAt + emailChanged := req.Email != existing.Email + if emailChanged { + if err := xrayMgr.UpdateXrayClientEmail(req.UUID, req.Email); err != nil { + http.Error(w, "update config email failed: "+err.Error(), http.StatusInternalServerError) + return + } + } + if err := statsStore.UpsertXrayClientMeta(r.Context(), meta); err != nil { + if emailChanged { + _ = xrayMgr.UpdateXrayClientEmail(req.UUID, existing.Email) + } + http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) + return + } + if req.ResetUsage { + if err := xrayMgr.resetNativeTrafficAccounting(r.Context(), statsStore, req.UUID, existing.Email); err != nil { + http.Error(w, "usage reset failed: "+err.Error(), http.StatusInternalServerError) + return + } + meta.TotalUplinkBytes = 0 + meta.TotalDownlinkBytes = 0 + } + xrayMgr.setNativeQuotaPolicy(&meta) + if meta.ExpiresAt != nil && !meta.ExpiresAt.After(time.Now()) { + xrayMgr.disconnectNativeClient(req.UUID) + } + if emailChanged { + xrayMgr.restartIfExternalRunning() + } + w.WriteHeader(http.StatusOK) +} + +func parseOptionalXrayExpiry(raw string) (*time.Time, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, nil + } + for _, layout := range []string{time.RFC3339, "2006-01-02T15:04", "2006-01-02"} { + if t, err := time.Parse(layout, raw); err == nil { + return &t, nil + } + } + return nil, fmt.Errorf("invalid expires_at (RFC3339, YYYY-MM-DDThh:mm, or YYYY-MM-DD required)") +} + +func handleXrayClientResetTraffic(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + var req struct { + UUID string `json:"uuid"` + ServerID string `json:"server_id,omitempty"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid json", http.StatusBadRequest) + return + } + req.UUID = strings.TrimSpace(req.UUID) + if req.UUID == "" { + http.Error(w, "uuid required", http.StatusBadRequest) + return + } + + ctx := r.Context() + if ms, remote, err := managedServerFromID(ctx, statsStore, req.ServerID); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller && !remoteXrayClientOwned(ctx, ms, req.UUID, sess.Username) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + req.ServerID = "" + body, _ := json.Marshal(req) + status, data, ct, err := proxyManagedServer(ctx, ms, http.MethodPost, "/api/xray/clients/reset-traffic", body, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + if statsStore == nil { + http.Error(w, "storage not available", http.StatusInternalServerError) + return + } + + existing, err := statsStore.GetXrayClientMeta(ctx, req.UUID) + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "client not found", http.StatusNotFound) + } else { + http.Error(w, "database error", http.StatusInternalServerError) + } + return + } + if sess := sessionFromCtx(ctx); sess != nil && sess.Role == RoleReseller && existing.OwnerUsername != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + if err := xrayMgr.resetNativeTrafficAccounting(ctx, statsStore, req.UUID, existing.Email); err != nil { + http.Error(w, "usage reset failed: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "uuid": req.UUID}) +} + +func handleXrayClientRemove(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + inboundTag := r.URL.Query().Get("inbound_tag") + uuid := r.URL.Query().Get("uuid") + if inboundTag == "" || uuid == "" { + http.Error(w, "inbound_tag and uuid required", http.StatusBadRequest) + return + } + if ms, remote, err := managedServerFromID(r.Context(), statsStore, requestedServerID(r)); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } else if remote { + if sess := sessionFromCtx(r.Context()); sess != nil && sess.Role == RoleReseller && !remoteXrayClientOwned(r.Context(), ms, uuid, sess.Username) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + remotePath := "/api/xray/clients/remove?inbound_tag=" + url.QueryEscape(inboundTag) + "&uuid=" + url.QueryEscape(uuid) + status, data, ct, err := proxyManagedServer(r.Context(), ms, http.MethodDelete, remotePath, nil, "application/json") + if err != nil { + http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway) + return + } + writeProxyResponse(w, status, data, ct) + return + } + + sess := sessionFromCtx(r.Context()) + if sess != nil && sess.Role == RoleReseller { + if statsStore == nil { + http.Error(w, "storage not available", http.StatusInternalServerError) + return + } + meta, err := statsStore.GetXrayClientMeta(r.Context(), uuid) + if err != nil || meta.OwnerUsername != sess.Username { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + if meta.InboundTag != "" { + inboundTag = meta.InboundTag + } + } + + if err := xrayMgr.RemoveXrayClient(inboundTag, uuid); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if statsStore != nil { + _ = statsStore.DeleteXrayClientMeta(r.Context(), uuid) + } + xrayMgr.restartIfExternalRunning() + w.WriteHeader(http.StatusNoContent) +} diff --git a/xray_native.go b/xray_native.go new file mode 100644 index 0000000..fe16225 --- /dev/null +++ b/xray_native.go @@ -0,0 +1,1513 @@ +package main + +// Pure-Go, in-process Xray emulator. +// +// This is the Xray equivalent of the in-process SSH server in main.go: instead +// of shelling out to an external `xray run -c config.json` subprocess, the +// supported protocols are spoken directly in Go and every accepted stream is +// tunnelled with the same copyWithRateLimit machinery the SSH side uses. +// +// Native emulator scope: +// - Protocols : VLESS and VMess AEAD (TCP + UDP commands) +// - VLESS Mux : Mux.Cool child TCP/UDP sessions, including XUDP metadata +// - Transports: raw TCP, WebSocket (RFC 6455), XHTTP/SplitHTTP +// - Security : TLS, none +// +// REALITY, gRPC and HTTPUpgrade are still deferred; unsupported commands are +// rejected explicitly instead of silently falling back. +// +// Native mode has its own DB-backed config/runtime path. It does not spawn or +// query the external xray binary and does not require /opt/sshpanel/xray to be +// installed. The JSON shape remains Xray-compatible so the same panel wizard can +// generate native and external configs. + +import ( + "bufio" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/sha1" + "crypto/tls" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/time/rate" +) + +// ---------- parsed config model ---------- + +// nativeXrayClient is one authorized user parsed from an inbound's clients array. +type nativeXrayClient struct { + id [16]byte // parsed UUID bytes, used as the fast lookup key + uuid string // canonical string form (for logs) + email string // stats label + + // VMess-only material, precomputed at parse time (nil/zero for VLESS). + cmdKey [16]byte // MD5(uuid || vmess magic) + authIDCipher cipher.Block // AES-128 over KDF16(cmdKey, "AES Auth ID Encryption") +} + +// nativeInbound is a single listener built from one JSON inbound entry. +type nativeInbound struct { + tag string + protocol string // "vless" | "vmess" | "ssh" (XHTTP->SSH tunnel) + listen string // bind host, default 0.0.0.0 + port int + transport string // "tcp" | "ws" | "xhttp" | ... + path string // ws/xhttp request path (default "/") + security string // "tls" | "" (none) + sharedPort bool // DragonCoreSSH public SSH/HTTP and TLS listeners own the socket + + // XHTTP/SplitHTTP transport options. Only the fields that affect the wire + // format are mirrored here; unsupported obfuscation/padding knobs are ignored + // leniently so existing panel configs keep working. + xhttpHost string + xhttpMode string + xhttpSessionPlacement string + xhttpSessionKey string + xhttpSeqPlacement string + xhttpSeqKey string + xhttpUplinkDataPlacement string + xhttpUplinkDataKey string + xhttpMaxEachPostBytes int64 + xhttpMaxBufferedPosts int + xhttpMaxHeaderBytes int + xhttpNoSSEHeader bool + xhttpSessions map[string]*nativeXHTTPSession + xhttpMu sync.Mutex + + tlsConfig *tls.Config // built when security == "tls" + + clientMu sync.RWMutex + clientsByID map[[16]byte]*nativeXrayClient + + // Per-connection bandwidth ceilings in bytes/sec (0 = unlimited). Sourced + // from the panel's default limits, matching the SSH tunnel behaviour. + upBytesPerSec int + downBytesPerSec int +} + +// ---------- listener manager ---------- + +type nativeXrayServer struct { + mu sync.Mutex + listeners []net.Listener + inboundsByTag map[string]*nativeInbound + running bool + startTime time.Time + shared atomic.Pointer[sharedXrayRouter] +} + +var nativeXray = &nativeXrayServer{} + +// nativeXHTTPListener groups all XHTTP inbounds that bind the same address. +// XHTTP is ordinary HTTP at the transport layer, so routing by the configured +// path lets VLESS/VMess and the DragonCore SSH tunnel safely share one TLS port. +// The most specific path wins: for example /ssh/ is checked before /. +type nativeXHTTPListener struct { + addr string + inbounds []*nativeInbound + tlsConfig *tls.Config + security string + headerSize int +} + +// nativeRunning reports whether the in-process Xray listeners are up. +func (s *nativeXrayServer) nativeRunning() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.running +} + +// start parses the config file and opens a listener for every supported +// inbound. It is idempotent-ish: callers (XrayManager) guard against double +// start, but start() will refuse if already running. +func (s *nativeXrayServer) start(configFile string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.running { + return fmt.Errorf("native xray already running") + } + beginNativeTransportAccepting() + started := false + defer func() { + if !started { + stopNativeTransportAccepting() + closeAllNativeTransportConnections() + } + }() + if configFile == "" { + return fmt.Errorf("native xray: no config file configured") + } + + inbounds, err := parseNativeInbounds(configFile) + if err != nil { + return err + } + if len(inbounds) == 0 { + return fmt.Errorf("native xray: no servable inbounds in %s", configFile) + } + if data, err := os.ReadFile(configFile); err != nil { return err } else if err := validateNativeInboundBindings(data); err != nil { return err } + + var opened []net.Listener + active := make(map[string]*nativeInbound, len(inbounds)) + xhttpGroups := make(map[string][]*nativeInbound) + var xhttpOrder []string + for _, ib := range inbounds { + if ib.sharedPort { + active[ib.tag] = ib + continue + } + if ib.isXHTTP() { + addr := net.JoinHostPort(ib.listen, strconv.Itoa(ib.port)) + if _, exists := xhttpGroups[addr]; !exists { + xhttpOrder = append(xhttpOrder, addr) + } + xhttpGroups[addr] = append(xhttpGroups[addr], ib) + active[ib.tag] = ib + continue + } + addr := net.JoinHostPort(ib.listen, strconv.Itoa(ib.port)) + ln, err := net.Listen("tcp", addr) + if err != nil { + // Roll back anything already opened so we don't leak listeners. + for _, l := range opened { + _ = l.Close() + } + return fmt.Errorf("native xray: listen %s (inbound %q): %w", addr, ib.tag, err) + } + + opened = append(opened, ln) + xrayGo(fmt.Sprintf("native xray accept loop %s", addr), func() { ib.acceptLoop(ln) }) + active[ib.tag] = ib + xrayLogf("native xray: serving %s/%s on %s (inbound %q, security=%s, %d clients)", + ib.protocol, ib.transport, addr, ib.tag, orNone(ib.security), ib.clientCount()) + } + shared, err := newSharedXrayRouter(inbounds) + if err != nil { + for _, l := range opened { _ = l.Close() } + return err + } + + for _, addr := range xhttpOrder { + group, err := newNativeXHTTPListener(addr, xhttpGroups[addr]) + if err != nil { + for _, l := range opened { + _ = l.Close() + } + return err + } + ln, err := net.Listen("tcp", addr) + if err != nil { + for _, l := range opened { + _ = l.Close() + } + return fmt.Errorf("native xray: listen %s (shared XHTTP): %w", addr, err) + } + // Track accepted sockets so stop/reload can close them. VPN transports are + // not subject to a global website-style connection ceiling. + serveLn := trackNativeListener(ln) + if group.security == "tls" { + serveLn = tls.NewListener(serveLn, group.tlsConfig) + } + opened = append(opened, serveLn) + xrayGo(fmt.Sprintf("native xray shared xhttp listener %s", addr), func() { group.serve(serveLn) }) + for _, ib := range group.inbounds { + xrayLogf("native xray: serving %s/%s on %s%s (inbound %q, security=%s, %d clients)", + ib.protocol, ib.transport, addr, ib.path, ib.tag, orNone(ib.security), ib.clientCount()) + } + } + + if shared != nil { + opened = append(opened, shared.listeners...) + s.shared.Store(shared) + for _, ib := range inbounds { + if ib.sharedPort { + xrayLogf("native xray: serving %s/%s on DragonCoreSSH public ports%s (inbound %q, %d clients)", ib.protocol, ib.transport, ib.path, ib.tag, ib.clientCount()) + } + } + if shared.xhttp != nil { + xrayGo("native xray shared public XHTTP", func() { shared.xhttp.serve(trackNativeListener(shared.httpListener)) }) + } + } + s.listeners = opened + s.inboundsByTag = active + s.running = true + s.startTime = time.Now() + started = true + return nil +} + +func (s *nativeXrayServer) stop() { + s.mu.Lock() + if !s.running && len(s.listeners) == 0 { + s.mu.Unlock() + return + } + stopNativeTransportAccepting() + listeners := append([]net.Listener(nil), s.listeners...) + inbounds := make([]*nativeInbound, 0, len(s.inboundsByTag)) + for _, ib := range s.inboundsByTag { + inbounds = append(inbounds, ib) + } + s.listeners = nil + s.inboundsByTag = nil + s.running = false + s.shared.Store(nil) + s.mu.Unlock() + + for _, l := range listeners { + _ = l.Close() + } + closeAllNativeTransportConnections() + for _, ib := range inbounds { + ib.closeAllXHTTPSessions() + } + xrayLogf("native xray: stopped") +} + +func (ib *nativeInbound) acceptLoop(ln net.Listener) { + defer xrayRecover(fmt.Sprintf("native xray accept loop inbound=%q", ib.tag)) + for { + c, err := ln.Accept() + if err != nil { + if isListenerClosed(err) { + return + } + xrayLogf("native xray: accept error on %s: %v", ln.Addr(), err) + continue + } + counted, ok := waitWrapTrackedNativeTransportConn(c) + if !ok { + time.Sleep(nativeOverloadBackoff) + continue + } + c = counted + xrayGo(fmt.Sprintf("native xray connection remote=%s", c.RemoteAddr()), func() { ib.serve(c) }) + } +} + +// serve terminates TLS + transport, then dispatches on protocol. +func (ib *nativeInbound) serve(raw net.Conn) { + defer xrayRecover(fmt.Sprintf("native xray serve inbound=%q remote=%s", ib.tag, raw.RemoteAddr())) + defer raw.Close() + + if tc, ok := raw.(*net.TCPConn); ok { + _ = tc.SetKeepAlive(true) + _ = tc.SetKeepAlivePeriod(30 * time.Second) + _ = tc.SetNoDelay(true) + } + + // --- security layer --- + var conn net.Conn = raw + if ib.security == "tls" { + tconn := tls.Server(raw, ib.tlsConfig) + _ = tconn.SetDeadline(time.Now().Add(tlsHandshakeTimeout)) + if err := tconn.Handshake(); err != nil { + logNativePreAuthRejection("native xray: tls handshake from %s failed: %v", raw.RemoteAddr(), err) + return + } + _ = tconn.SetDeadline(time.Time{}) + conn = tconn + } + + // --- transport layer --- + var stream net.Conn = conn + switch ib.transport { + case "tcp", "raw", "": + // stream is already the protocol stream + case "ws", "websocket": + _ = conn.SetDeadline(time.Now().Add(tlsHandshakeTimeout)) + ws, err := wsServerHandshake(conn, ib.path) + if err != nil { + logNativePreAuthRejection("native xray: ws handshake from %s failed: %v", raw.RemoteAddr(), err) + return + } + _ = conn.SetDeadline(time.Time{}) + stream = ws + case "xhttp", "splithttp": + xrayLogf("native xray: inbound %q got raw connection for XHTTP; this transport is served by http.Server", ib.tag) + return + default: + xrayLogf("native xray: inbound %q transport %q not supported yet; dropping conn from %s", + ib.tag, ib.transport, raw.RemoteAddr()) + return + } + + // --- protocol layer --- + switch ib.protocol { + case "vless": + ib.handleVLESS(stream, raw.RemoteAddr()) + case "vmess": + ib.handleVMess(stream, raw.RemoteAddr()) + default: + xrayLogf("native xray: inbound %q protocol %q not supported yet; dropping conn from %s", + ib.tag, ib.protocol, raw.RemoteAddr()) + } +} + +// ---------- VLESS ---------- +// +// VLESS request header (client -> server): +// 1 byte version (0) +// 16 bytes UUID +// 1 byte addon length M +// M bytes addons (flow etc.) — skipped +// 1 byte command (1=TCP, 2=UDP, 3=Mux) +// for TCP/UDP only: +// 2 bytes port (big endian) +// 1 byte address type (1=IPv4, 2=domain, 3=IPv6) +// ... address +// for Mux: +// ... Mux.Cool/XUDP frames immediately after the command byte +// ... payload +// Response (server -> client): 1 byte version echo, 1 byte addon length (0). + +const ( + vlessCmdTCP = 1 + vlessCmdUDP = 2 + vlessCmdMux = 3 + + atypIPv4 = 1 + atypDomain = 2 + atypIPv6 = 3 +) + +func (ib *nativeInbound) handleVLESS(stream net.Conn, remote net.Addr) { + defer xrayRecover(fmt.Sprintf("native xray VLESS inbound=%q remote=%s", ib.tag, remote)) + xrayTracef("native xray: vless handshake start inbound=%q transport=%s remote=%s", ib.tag, ib.transport, remote) + _ = stream.SetReadDeadline(time.Now().Add(30 * time.Second)) + + head := make([]byte, 1+16+1) // version + uuid + addonLen + if _, err := io.ReadFull(stream, head); err != nil { + ib.logVLESSReadFailure("handshake", remote, "", err) + return + } + version := head[0] + var id [16]byte + copy(id[:], head[1:17]) + + client := ib.getNativeClient(id) + if client == nil { + logNativePreAuthRejection("native xray: inbound %q rejected unknown VLESS uuid from %s", ib.tag, remote) + return + } + if reason := xrayMgr.nativeClientAccessDenied(client.uuid); reason != "" { + xrayLogf("native xray: inbound %q rejected VLESS user %s: %s", ib.tag, client.email, reason) + return + } + + if addonLen := int(head[17]); addonLen > 0 { + if _, err := io.CopyN(io.Discard, stream, int64(addonLen)); err != nil { + xrayLogf("native xray: vless addon read failed inbound=%q user=%s: %v", ib.tag, client.email, err) + return + } + } + + var cmd [1]byte + if _, err := io.ReadFull(stream, cmd[:]); err != nil { + ib.logVLESSReadFailure("command", remote, client.email, err) + return + } + + var host string + var port uint16 + if cmd[0] == vlessCmdTCP || cmd[0] == vlessCmdUDP { + var portBuf [2]byte + if _, err := io.ReadFull(stream, portBuf[:]); err != nil { + xrayLogf("native xray: vless port read failed inbound=%q user=%s: %v", ib.tag, client.email, err) + return + } + port = binary.BigEndian.Uint16(portBuf[:]) + + var err error + host, err = readProxyAddress(stream) + if err != nil { + xrayLogf("native xray: inbound %q VLESS bad address from %s: %v", ib.tag, remote, err) + return + } + if isNativeDNSSinkTarget(host) { + _ = stream.SetReadDeadline(time.Time{}) + _ = stream.SetWriteDeadline(time.Now().Add(time.Second)) + _, _ = stream.Write([]byte{version, 0}) + xrayTracef("native xray: inbound %q fast-ignored DNS sink target cmd=%d user=%s host=%q port=%d remote=%s", ib.tag, cmd[0], client.email, host, port, remote) + return + } + if invalidNativeDestination(host, port) { + xrayTracef("native xray: inbound %q rejected invalid VLESS target cmd=%d user=%s host=%q port=%d remote=%s", ib.tag, cmd[0], client.email, host, port, remote) + return + } + } + _ = stream.SetReadDeadline(time.Time{}) + + switch cmd[0] { + case vlessCmdTCP, vlessCmdUDP, vlessCmdMux: + default: + xrayLogf("native xray: inbound %q VLESS command %d not supported yet", ib.tag, cmd[0]) + return + } + releaseConnection, quotaState, ok := xrayMgr.acquireNativeClientConnection(client.uuid, client.email, stream) + if !ok { + return + } + defer releaseConnection() + + // VLESS response header must be sent before relaying payload. CommandMux is + // special: official Xray does not read a target from the VLESS header for it; + // the following bytes are Mux.Cool/XUDP frames. Reading port/address here + // deadlocks muxed UDP clients and shows up as QUIC/YouTube stalls. + if _, err := stream.Write([]byte{version, 0}); err != nil { + xrayLogf("native xray: vless response write failed inbound=%q user=%s: %v", ib.tag, client.email, err) + return + } + + switch cmd[0] { + case vlessCmdTCP: + backend, target, err := ib.nativeDialTCP(host, port) + if err != nil { + xrayLogf("native xray: inbound %q VLESS TCP dial %s failed: %v", ib.tag, target, err) + return + } + ib.nativeSuccessLogf("native xray: vless/tcp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag) + nativeTunnel(stream, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter()) + case vlessCmdUDP: + backend, target, err := ib.nativeDialUDP(host, port) + if err != nil { + xrayLogf("native xray: inbound %q VLESS UDP dial %s failed: %v", ib.tag, target, err) + return + } + ib.nativeSuccessLogf("native xray: vless/udp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag) + nativeVLESSUDPTunnel(stream, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter()) + case vlessCmdMux: + ib.nativeSuccessLogf("native xray: vless/mux user=%s remote=%s (inbound %q)", client.email, remote, ib.tag) + ib.nativeVLESSMuxTunnel(stream, client.uuid, client.email, quotaState) + } +} + +func (ib *nativeInbound) logVLESSReadFailure(stage string, remote net.Addr, email string, err error) { + if ib.isXHTTP() && isNativeDeadlineError(err) { + if email == "" { + xrayTracef("native xray: vless %s timed out inbound=%q transport=%s remote=%s: %v", stage, ib.tag, ib.transport, remote, err) + } else { + xrayTracef("native xray: vless %s timed out inbound=%q transport=%s user=%s remote=%s: %v", stage, ib.tag, ib.transport, email, remote, err) + } + return + } + if email == "" { + logNativePreAuthRejection("native xray: vless %s failed inbound=%q transport=%s remote=%s: %v", stage, ib.tag, ib.transport, remote, err) + } else { + xrayLogf("native xray: vless %s failed inbound=%q transport=%s user=%s remote=%s: %v", stage, ib.tag, ib.transport, email, remote, err) + } +} + +func isNativeDeadlineError(err error) bool { + if errors.Is(err, os.ErrDeadlineExceeded) { + return true + } + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} + +func invalidNativeDestination(host string, port uint16) bool { + host = strings.TrimSpace(normalizeNativeTargetHost(host)) + if host == "" || port == 0 { + return true + } + if ip := net.ParseIP(stripNativeIPZone(host)); ip != nil { + return ip.IsUnspecified() + } + return false +} + +func isNativeDNSSinkTarget(host string) bool { + host = strings.TrimSpace(normalizeNativeTargetHost(host)) + if host == "" { + return false + } + ip := net.ParseIP(stripNativeIPZone(host)) + return ip != nil && ip.IsUnspecified() +} + +func (ib *nativeInbound) nativeSuccessLogf(format string, args ...interface{}) { + if ib != nil && ib.isXHTTP() { + xrayTracef(format, args...) + return + } + xrayLogf(format, args...) +} + +// readProxyAddress reads a VMess/VLESS-style address (type byte + address). +func readProxyAddress(r io.Reader) (string, error) { + var t [1]byte + if _, err := io.ReadFull(r, t[:]); err != nil { + return "", err + } + switch t[0] { + case atypIPv4: + b := make([]byte, 4) + if _, err := io.ReadFull(r, b); err != nil { + return "", err + } + return net.IP(b).String(), nil + case atypDomain: + var l [1]byte + if _, err := io.ReadFull(r, l[:]); err != nil { + return "", err + } + d := make([]byte, int(l[0])) + if _, err := io.ReadFull(r, d); err != nil { + return "", err + } + return string(d), nil + case atypIPv6: + b := make([]byte, 16) + if _, err := io.ReadFull(r, b); err != nil { + return "", err + } + return net.IP(b).String(), nil + default: + return "", fmt.Errorf("unknown address type %d", t[0]) + } +} + +func (ib *nativeInbound) nativeDialTCP(host string, port uint16) (net.Conn, string, error) { + return ib.nativeDialTarget("tcp", host, port) +} + +func (ib *nativeInbound) nativeDialUDP(host string, port uint16) (net.Conn, string, error) { + return ib.nativeDialTarget("udp", host, port) +} + +func nativeDialTCP(host string, port uint16) (net.Conn, string, error) { + return nativeDialTarget("tcp", host, port) +} + +func nativeDialUDP(host string, port uint16) (net.Conn, string, error) { + return nativeDialTarget("udp", host, port) +} + +func nativeDialTarget(network, host string, port uint16) (net.Conn, string, error) { + return nativeDialTargetWithSource(network, host, port, "") +} + +func (ib *nativeInbound) nativeDialTarget(network, host string, port uint16) (net.Conn, string, error) { + return nativeDialTargetWithSource(network, host, port, ib.listen) +} + +func nativeDialTargetWithSource(network, host string, port uint16, sourceHost string) (net.Conn, string, error) { + targetHost := normalizeNativeTargetHost(host) + target := net.JoinHostPort(targetHost, strconv.Itoa(int(port))) + dialNetwork := nativeDialNetwork(network, targetHost) + + // IPv6 tunnel traffic must remain IPv6, but binding to the inbound/listen + // address is not always valid on providers with routed /128s, policy routing, + // or multiple IPv6 addresses. Try the source-bound dial first when it makes + // sense, then fall back to the kernel's normal source selection before giving + // up. This mirrors external Xray/freedom behavior more closely and prevents + // client-side ERR_CONNECTION_CLOSED when the first IPv6 source choice fails. + var attempts []net.Addr + if local := nativeLocalAddrForDial(dialNetwork, targetHost, sourceHost); local != nil { + attempts = append(attempts, local) + } + attempts = append(attempts, nil) + + var lastErr error + for i, local := range attempts { + ctx, cancel := context.WithTimeout(context.Background(), directTCPIPDialTimeout) + d := &net.Dialer{Timeout: directTCPIPDialTimeout, KeepAlive: 30 * time.Second} + if local != nil { + d.LocalAddr = local + } + conn, err := d.DialContext(ctx, dialNetwork, target) + cancel() + if err == nil { + if i > 0 && len(attempts) > 1 { + xrayLogf("native xray: outbound dial recovered target=%s network=%s using auto source after bound source failed", target, dialNetwork) + } + return conn, target, nil + } + lastErr = err + if local != nil { + xrayLogf("native xray: outbound dial target=%s network=%s source=%s failed, retrying auto source: %v", target, dialNetwork, local.String(), err) + } + } + return nil, target, lastErr +} + +func nativeDialNetwork(base, host string) string { + if base != "tcp" && base != "udp" { + return base + } + ip := net.ParseIP(normalizeNativeTargetHost(host)) + if ip == nil { + // Domain targets must remain dual-stack. Let Go's dialer use the server's + // resolver and Happy Eyeballs instead of forcing IPv4. This matches the + // expected behavior when the Android client has IPv6 route enabled. + return base + } + if ip.To4() != nil { + return base + "4" + } + return base + "6" +} + +func nativeLocalAddrForDial(network, targetHost, sourceHost string) net.Addr { + base := network + if strings.HasSuffix(base, "4") || strings.HasSuffix(base, "6") { + base = base[:len(base)-1] + } + if base != "tcp" && base != "udp" { + return nil + } + targetIP := net.ParseIP(normalizeNativeTargetHost(targetHost)) + if targetIP == nil { + return nil + } + sourceIP := net.ParseIP(normalizeNativeListenHost(sourceHost)) + if sourceIP == nil || sourceIP.IsUnspecified() { + return nil + } + // The tunnel must preserve the target address family. When the client sends + // an IPv6 destination, bind the outbound socket to the inbound/listen IPv6 + // address so Linux does not select a different or unrouted IPv6 source. This + // fixes the case where the Android client has IPv6 enabled and sends AAAA + // destinations through VLESS/VMess. Do not bind an IPv4 source for an IPv6 + // target, or the dial will fail before leaving the server. + if targetIP.To4() == nil { + if sourceIP.To4() != nil { + return nil + } + if base == "tcp" { + return &net.TCPAddr{IP: sourceIP} + } + return &net.UDPAddr{IP: sourceIP} + } + if sourceIP.To4() == nil { + return nil + } + if base == "tcp" { + return &net.TCPAddr{IP: sourceIP} + } + return &net.UDPAddr{IP: sourceIP} +} + +func normalizeNativeTargetHost(raw string) string { + v := strings.TrimSpace(raw) + if v == "" { + return v + } + if h, _, err := net.SplitHostPort(v); err == nil { + v = strings.TrimSpace(h) + } + for len(v) >= 2 && strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") { + v = strings.TrimSpace(v[1 : len(v)-1]) + } + return v +} + +// ---------- bidirectional tunnel + traffic metering ---------- + +// nativeTunnel pipes bytes between the decoded client stream and the dialed +// backend, applying per-direction rate limits and accounting traffic against +// the client's email so the panel's online detection keeps working. It mirrors +// handleDirectTCPIP in main.go. +func nativeTunnel(client io.ReadWriteCloser, backend net.Conn, uuid, email string, quotaState *xrayNativeQuotaState, up, down *rate.Limiter) { + defer xrayRecover(fmt.Sprintf("native xray TCP tunnel user=%s", email)) + + upMeter := newTrafficMeter(uuid, email, true, quotaState) + downMeter := newTrafficMeter(uuid, email, false, quotaState) + + var wg sync.WaitGroup + var closeOnce sync.Once + ctx, cancel := context.WithCancel(context.Background()) + closeAll := func() { + closeOnce.Do(func() { + cancel() + _ = backend.Close() + _ = client.Close() + }) + } + + wg.Add(1) + xrayGo("native xray TCP uplink", func() { // client -> backend + defer wg.Done() + defer closeAll() + _, _ = copyWithRateLimitContext(ctx, xrayQuotaMeteredWriter{w: backend, meter: upMeter, ctx: ctx}, client, up) + if cw, ok := backend.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }) + + wg.Add(1) + xrayGo("native xray TCP downlink", func() { // backend -> client + defer wg.Done() + defer closeAll() + _, _ = copyWithRateLimitContext(ctx, xrayQuotaMeteredWriter{w: client, meter: downMeter, ctx: ctx}, backend, down) + }) + + wg.Wait() + upMeter.flush() + downMeter.flush() + closeAll() +} + +// trafficMeter accumulates bytes for one direction and flushes them to the +// stats manager in batches to avoid locking on every write. +type trafficMeter struct { + uuid string + email string + uplink bool + n int64 + quotaGeneration uint64 + state *xrayNativeQuotaState +} + +const trafficFlushThreshold = 1024 * 1024 + +func newTrafficMeter(uuid, email string, uplink bool, state *xrayNativeQuotaState) *trafficMeter { + t := &trafficMeter{uuid: uuid, email: email, uplink: uplink, state: state} + t.syncQuotaGeneration() + return t +} + +func (t *trafficMeter) add(n int) { + t.syncQuotaGeneration() + t.n += int64(n) + if t.n >= trafficFlushThreshold { + t.flush() + } +} + +func (t *trafficMeter) flush() { + t.syncQuotaGeneration() + if t.n == 0 || t.email == "" { + return + } + if t.uplink { + xrayMgr.recordNativeTraffic(t.uuid, t.email, t.n, 0, t.quotaGeneration, t.state) + } else { + xrayMgr.recordNativeTraffic(t.uuid, t.email, 0, t.n, t.quotaGeneration, t.state) + } + t.n = 0 +} + +func (t *trafficMeter) syncQuotaGeneration() { + var generation uint64 + if t.state != nil { + t.state.mu.Lock() + generation = t.state.generation + t.state.mu.Unlock() + } + if t.quotaGeneration == 0 { + t.quotaGeneration = generation + return + } + if generation != t.quotaGeneration { + t.n = 0 + t.quotaGeneration = generation + } +} + +func (ib *nativeInbound) upLimiter() *rate.Limiter { return newByteLimiter(ib.upBytesPerSec) } +func (ib *nativeInbound) downLimiter() *rate.Limiter { return newByteLimiter(ib.downBytesPerSec) } + +func newByteLimiter(bytesPerSec int) *rate.Limiter { + if bytesPerSec <= 0 { + return nil + } + return rate.NewLimiter(rate.Limit(bytesPerSec), bytesPerSec) +} + +// ---------- WebSocket transport (RFC 6455, server side) ---------- + +const wsMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" +const wsMaxFrame = 16 * 1024 * 1024 + +// wsServerHandshake performs the server side of the WebSocket upgrade over an +// already-established (optionally TLS) connection, then returns a net.Conn whose +// Read/Write speak binary WebSocket frames. +func wsServerHandshake(conn net.Conn, wantPath string) (*websocketConn, error) { + br := bufio.NewReader(conn) + req, err := http.ReadRequest(br) + if err != nil { + return nil, err + } + if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") { + return nil, errors.New("missing websocket upgrade") + } + key := req.Header.Get("Sec-WebSocket-Key") + if key == "" { + return nil, errors.New("missing Sec-WebSocket-Key") + } + if i := strings.IndexByte(wantPath, '?'); i >= 0 { + wantPath = wantPath[:i] + } + if wantPath != "" && wantPath != "/" && req.URL.Path != wantPath { + return nil, fmt.Errorf("ws path mismatch: got %q want %q", req.URL.Path, wantPath) + } + + var early []byte + proto := req.Header.Get("Sec-WebSocket-Protocol") + if proto != "" { + if ed, derr := base64.RawURLEncoding.DecodeString(proto); derr == nil { + early = ed + } + } + + sum := sha1.Sum([]byte(key + wsMagicGUID)) + accept := base64.StdEncoding.EncodeToString(sum[:]) + resp := "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + accept + "\r\n" + if proto != "" { + resp += "Sec-WebSocket-Protocol: " + proto + "\r\n" + } + resp += "\r\n" + if _, err := conn.Write([]byte(resp)); err != nil { + return nil, err + } + return &websocketConn{Conn: conn, r: br, early: early}, nil +} + +// websocketConn adapts a WebSocket data stream to a net.Conn. Client frames are +// masked; server frames are written unmasked as binary frames. +type websocketConn struct { + net.Conn + r *bufio.Reader + early []byte + readBuf []byte // decoded payload not yet consumed by Read + wmu sync.Mutex +} + +func (c *websocketConn) Read(p []byte) (int, error) { + if len(c.early) > 0 { + n := copy(p, c.early) + c.early = c.early[n:] + return n, nil + } + for len(c.readBuf) == 0 { + payload, opcode, err := c.readFrame() + if err != nil { + return 0, err + } + switch opcode { + case 0x8: // close + return 0, io.EOF + case 0x9: // ping -> pong + _ = c.writeFrame(0xA, payload) + continue + case 0xA: // pong -> ignore + continue + default: // 0x0 continuation, 0x1 text, 0x2 binary -> treat as data + c.readBuf = payload + } + } + n := copy(p, c.readBuf) + c.readBuf = c.readBuf[n:] + return n, nil +} + +func (c *websocketConn) readFrame() (payload []byte, opcode byte, err error) { + var h [2]byte + if _, err = io.ReadFull(c.r, h[:]); err != nil { + return nil, 0, err + } + opcode = h[0] & 0x0f + masked := h[1]&0x80 != 0 + length := int64(h[1] & 0x7f) + switch length { + case 126: + var ext [2]byte + if _, err = io.ReadFull(c.r, ext[:]); err != nil { + return nil, 0, err + } + length = int64(binary.BigEndian.Uint16(ext[:])) + case 127: + var ext [8]byte + if _, err = io.ReadFull(c.r, ext[:]); err != nil { + return nil, 0, err + } + length = int64(binary.BigEndian.Uint64(ext[:])) + } + if length < 0 || length > wsMaxFrame { + return nil, 0, fmt.Errorf("ws frame too large: %d", length) + } + var mask [4]byte + if masked { + if _, err = io.ReadFull(c.r, mask[:]); err != nil { + return nil, 0, err + } + } + payload = make([]byte, length) + if _, err = io.ReadFull(c.r, payload); err != nil { + return nil, 0, err + } + if masked { + for i := range payload { + payload[i] ^= mask[i&3] + } + } + return payload, opcode, nil +} + +func (c *websocketConn) Write(p []byte) (int, error) { + if err := c.writeFrame(0x2, p); err != nil { + return 0, err + } + return len(p), nil +} + +func (c *websocketConn) writeFrame(opcode byte, payload []byte) error { + c.wmu.Lock() + defer c.wmu.Unlock() + + n := len(payload) + var header []byte + b0 := byte(0x80) | opcode // FIN + opcode + switch { + case n < 126: + header = []byte{b0, byte(n)} + case n <= 0xffff: + header = []byte{b0, 126, byte(n >> 8), byte(n)} + default: + header = make([]byte, 10) + header[0] = b0 + header[1] = 127 + binary.BigEndian.PutUint64(header[2:], uint64(n)) + } + frame := make([]byte, len(header)+n) + copy(frame, header) + copy(frame[len(header):], payload) + _, err := c.Conn.Write(frame) + return err +} + +// ---------- config parsing ---------- + +// nativeXrayConfigFile mirrors the subset of the Xray JSON config the native +// server understands. +type nativeXrayConfigFile struct { + Inbounds []nativeInboundJSON `json:"inbounds"` +} + +type nativeXHTTPSettingsJSON struct { + Host string `json:"host"` + Path string `json:"path"` + Mode string `json:"mode"` + NoSSEHeader bool `json:"noSSEHeader"` + SessionIDPlacement string `json:"sessionIDPlacement"` + SessionIDKey string `json:"sessionIDKey"` + SeqPlacement string `json:"seqPlacement"` + SeqKey string `json:"seqKey"` + UplinkDataPlacement string `json:"uplinkDataPlacement"` + UplinkDataKey string `json:"uplinkDataKey"` + ScMaxEachPostBytes *nativeRangeJSON `json:"scMaxEachPostBytes"` + ScMaxBufferedPosts int `json:"scMaxBufferedPosts"` + ServerMaxHeaderBytes int `json:"serverMaxHeaderBytes"` +} + +type nativeRangeJSON struct { + From int64 `json:"from"` + To int64 `json:"to"` +} + +type nativeInboundJSON struct { + Tag string `json:"tag"` + DragoncoreSharedPort bool `json:"dragoncoreSharedPort,omitempty"` + Protocol string `json:"protocol"` + Listen string `json:"listen"` + Port json.RawMessage `json:"port"` + Settings struct { + Clients []struct { + ID string `json:"id"` + Password string `json:"password"` + Email string `json:"email"` + } `json:"clients"` + Users []struct { + ID string `json:"id"` + Password string `json:"password"` + Email string `json:"email"` + } `json:"users"` + } `json:"settings"` + StreamSettings struct { + Network string `json:"network"` + Security string `json:"security"` + TLSSettings struct { + Certificates []struct { + CertificateFile string `json:"certificateFile"` + KeyFile string `json:"keyFile"` + } `json:"certificates"` + } `json:"tlsSettings"` + WSSettings struct { + Path string `json:"path"` + } `json:"wsSettings"` + XHTTPSettings nativeXHTTPSettingsJSON `json:"xhttpSettings"` + SplitHTTPSettings nativeXHTTPSettingsJSON `json:"splithttpSettings"` + } `json:"streamSettings"` +} + +// validateNativeInboundBindings checks the listener topology before a visual or +// raw-JSON update replaces the running native config. It intentionally mirrors +// the startup rules so an invalid shared-port edit is rejected before the last +// working file is overwritten. +func validateNativeInboundBindings(data []byte) error { + var cf nativeXrayConfigFile + if err := json.Unmarshal(data, &cf); err != nil { + return fmt.Errorf("native xray: parse config: %w", err) + } + type binding struct { + tag string + xhttp bool + path string + security string + certFile string + keyFile string + } + groups := make(map[string][]binding) + sharedPaths := map[string]string{} + for _, in := range cf.Inbounds { + proto := strings.ToLower(strings.TrimSpace(in.Protocol)) + if proto != "ssh" && !xrayClientProtos[proto] { + continue + } + port, ok := parseSinglePort(in.Port) + if !ok { + return fmt.Errorf("native xray: inbound %q has an unsupported port", in.Tag) + } + network := strings.ToLower(firstNonEmpty(in.StreamSettings.Network, "tcp")) + isXHTTP := network == "xhttp" || network == "splithttp" + if proto == "ssh" && !isXHTTP { + return fmt.Errorf("native xray: inbound %q protocol ssh requires XHTTP", in.Tag) + } + item := binding{tag: in.Tag, xhttp: isXHTTP, security: strings.ToLower(strings.TrimSpace(in.StreamSettings.Security))} + if item.security == "none" { + item.security = "" + } + if isXHTTP { + xh := mergeNativeXHTTPSettings(in.StreamSettings.XHTTPSettings, in.StreamSettings.SplitHTTPSettings) + item.path = normalizeXHTTPPath(firstNonEmpty(xh.Path, "/xhttp")) + } + if in.DragoncoreSharedPort { + if err := validateSharedXrayInbound(in); err != nil { return err } + path := in.StreamSettings.WSSettings.Path + if isXHTTP { path = mergeNativeXHTTPSettings(in.StreamSettings.XHTTPSettings, in.StreamSettings.SplitHTTPSettings).Path } + path, _ = sharedXrayPath(path) + for prior, tag := range sharedPaths { + if path == prior || strings.HasPrefix(path, prior+"/") || strings.HasPrefix(prior, path+"/") { + return fmt.Errorf("shared Xray paths %s (%s) and %s (%s) overlap", prior, tag, path, in.Tag) + } + } + sharedPaths[path] = in.Tag + continue + } + if len(in.StreamSettings.TLSSettings.Certificates) > 0 { + item.certFile = strings.TrimSpace(in.StreamSettings.TLSSettings.Certificates[0].CertificateFile) + item.keyFile = strings.TrimSpace(in.StreamSettings.TLSSettings.Certificates[0].KeyFile) + } + host := normalizeNativeListenHost(firstNonEmpty(in.Listen, "0.0.0.0")) + addr := net.JoinHostPort(host, strconv.Itoa(port)) + groups[addr] = append(groups[addr], item) + } + for addr, items := range groups { + if len(items) < 2 { + continue + } + paths := make(map[string]string, len(items)) + first := items[0] + for _, item := range items { + if !item.xhttp { + return fmt.Errorf("native xray: multiple inbounds on %s require XHTTP path routing", addr) + } + if previous, exists := paths[item.path]; exists { + return fmt.Errorf("native xray: XHTTP inbounds %q and %q use the same path %s on %s", previous, item.tag, item.path, addr) + } + paths[item.path] = item.tag + if item.security != first.security { + return fmt.Errorf("native xray: XHTTP inbounds sharing %s must use the same TLS setting", addr) + } + if item.security == "tls" && (item.certFile != first.certFile || item.keyFile != first.keyFile) { + return fmt.Errorf("native xray: XHTTP inbounds sharing %s must use the same TLS certificate", addr) + } + } + } + return nil +} + +// parseNativeInbounds reads the Xray config file and returns one nativeInbound +// per servable client-bearing inbound. Unsupported inbounds (api dokodemo-door, +// freedom, etc.) are silently skipped. +func parseNativeInbounds(configFile string) ([]*nativeInbound, error) { + data, err := os.ReadFile(configFile) + if err != nil { + return nil, err + } + var cf nativeXrayConfigFile + if err := json.Unmarshal(data, &cf); err != nil { + return nil, fmt.Errorf("native xray: parse %s: %w", configFile, err) + } + + upBps, downBps := defaultNativeLimits() + + var out []*nativeInbound + for _, in := range cf.Inbounds { + proto := strings.ToLower(strings.TrimSpace(in.Protocol)) + // "ssh" is a DragonCore extension: an XHTTP inbound whose decoded byte + // stream is handed to the SSH server (handleConn) instead of a proxy + // protocol. It carries no proxy clients (auth is the SSH account), so it + // intentionally bypasses the client-bearing protocol gate below. + if proto != "ssh" && !xrayClientProtos[proto] { + continue // only vless/vmess/trojan carry clients; skip api/freedom/etc. + } + port, ok := parseSinglePort(in.Port) + if !ok { + xrayLogf("native xray: inbound %q has unsupported port form; skipping", in.Tag) + continue + } + + ib := &nativeInbound{ + tag: in.Tag, + protocol: proto, + listen: normalizeNativeListenHost(firstNonEmpty(in.Listen, "0.0.0.0")), + port: port, + transport: strings.ToLower(firstNonEmpty(in.StreamSettings.Network, "tcp")), + security: strings.ToLower(strings.TrimSpace(in.StreamSettings.Security)), + sharedPort: in.DragoncoreSharedPort, + clientsByID: make(map[[16]byte]*nativeXrayClient), + upBytesPerSec: upBps, + downBytesPerSec: downBps, + } + if ib.security == "none" { + ib.security = "" + } + + switch ib.transport { + case "ws", "websocket": + ib.path = firstNonEmpty(in.StreamSettings.WSSettings.Path, "/") + case "xhttp", "splithttp": + xh := mergeNativeXHTTPSettings(in.StreamSettings.XHTTPSettings, in.StreamSettings.SplitHTTPSettings) + ib.path = normalizeXHTTPPath(firstNonEmpty(xh.Path, "/xhttp")) + ib.xhttpHost = strings.TrimSpace(xh.Host) + ib.xhttpMode = strings.ToLower(strings.TrimSpace(xh.Mode)) + ib.xhttpSessionPlacement = strings.ToLower(strings.TrimSpace(xh.SessionIDPlacement)) + ib.xhttpSessionKey = strings.TrimSpace(xh.SessionIDKey) + ib.xhttpSeqPlacement = strings.ToLower(strings.TrimSpace(xh.SeqPlacement)) + ib.xhttpSeqKey = strings.TrimSpace(xh.SeqKey) + ib.xhttpUplinkDataPlacement = strings.ToLower(strings.TrimSpace(xh.UplinkDataPlacement)) + ib.xhttpUplinkDataKey = strings.TrimSpace(xh.UplinkDataKey) + ib.xhttpNoSSEHeader = xh.NoSSEHeader + ib.xhttpMaxHeaderBytes = xh.ServerMaxHeaderBytes + ib.xhttpMaxEachPostBytes = 1_000_000 + if xh.ScMaxEachPostBytes != nil && xh.ScMaxEachPostBytes.To > 0 { + ib.xhttpMaxEachPostBytes = xh.ScMaxEachPostBytes.To + } + ib.xhttpMaxBufferedPosts = xh.ScMaxBufferedPosts + if ib.xhttpMaxBufferedPosts <= 0 { + ib.xhttpMaxBufferedPosts = nativeXHTTPBufferedPostLimit() + } + ib.xhttpSessions = make(map[string]*nativeXHTTPSession) + } + + // TLS certificate: prefer the inbound's own tlsSettings, else fall back + // to the panel's top-level cert/key. + if ib.security == "tls" { + tc, err := buildInboundTLS(in) + if err != nil { + xrayLogf("native xray: inbound %q TLS disabled: %v; skipping", in.Tag, err) + continue + } + ib.tlsConfig = tc + } + + // XHTTP->SSH inbounds have no proxy clients: the SSH handshake performed by + // handleConn is the authentication step. Skip proxy-client loading and the + // clientCount()==0 gate below, but enforce that "ssh" is only valid on the + // XHTTP transport (that is the only path that reaches dispatchXHTTPConn). + if ib.protocol == "ssh" { + if !ib.isXHTTP() { + xrayLogf("native xray: inbound %q protocol \"ssh\" requires xhttp transport; skipping", in.Tag) + continue + } + out = append(out, ib) + continue + } + + configClients := in.Settings.Clients + if len(in.Settings.Users) > 0 { + configClients = append(configClients, in.Settings.Users...) + } + for _, c := range configClients { + raw := c.ID + if raw == "" { + raw = c.Password // some protocols reuse password as id + } + if err := ib.addNativeClient(proto, raw, c.Email); err != nil { + xrayLogf("native xray: inbound %q skipping client %q: %v", in.Tag, raw, err) + } + } + if statsStore != nil && in.Tag != "" { + metas, err := statsStore.ListXrayClientsByInbound(context.Background(), in.Tag) + if err != nil { + xrayLogf("native xray: inbound %q database clients unavailable: %v", in.Tag, err) + } else { + for _, m := range metas { + if err := ib.addNativeClient(proto, m.UUID, firstNonEmpty(m.Email, m.Name, m.UUID)); err != nil { + xrayLogf("native xray: inbound %q skipping DB client %q: %v", in.Tag, m.UUID, err) + } + } + } + } + + if ib.clientCount() == 0 { + xrayLogf("native xray: inbound %q has no valid clients; skipping", in.Tag) + continue + } + out = append(out, ib) + } + return out, nil +} + +func (ib *nativeInbound) makeNativeClient(proto, raw, email string) (*nativeXrayClient, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, fmt.Errorf("empty uuid") + } + id, err := parseUUID(raw) + if err != nil { + return nil, err + } + if email == "" { + email = raw + } + nc := &nativeXrayClient{id: id, uuid: raw, email: email} + if proto == "vmess" { + nc.cmdKey = vmessCmdKey(id) + block, err := aes.NewCipher(vmessKDF16(nc.cmdKey[:], kdfLabelAuthIDEncryptionKey)) + if err != nil { + return nil, fmt.Errorf("vmess cipher init: %w", err) + } + nc.authIDCipher = block + } + return nc, nil +} + +func (ib *nativeInbound) addNativeClient(proto, raw, email string) error { + nc, err := ib.makeNativeClient(proto, raw, email) + if err != nil { + return err + } + ib.clientMu.Lock() + if ib.clientsByID == nil { + ib.clientsByID = make(map[[16]byte]*nativeXrayClient) + } + ib.clientsByID[nc.id] = nc + ib.clientMu.Unlock() + return nil +} + +func (ib *nativeInbound) getNativeClient(id [16]byte) *nativeXrayClient { + ib.clientMu.RLock() + defer ib.clientMu.RUnlock() + return ib.clientsByID[id] +} + +func (ib *nativeInbound) removeNativeClient(uuid string) bool { + id, err := parseUUID(uuid) + if err != nil { + return false + } + ib.clientMu.Lock() + _, existed := ib.clientsByID[id] + delete(ib.clientsByID, id) + ib.clientMu.Unlock() + return existed +} + +func (ib *nativeInbound) updateNativeClientEmail(uuid, email string) bool { + id, err := parseUUID(uuid) + if err != nil || strings.TrimSpace(email) == "" { + return false + } + ib.clientMu.Lock() + defer ib.clientMu.Unlock() + old := ib.clientsByID[id] + if old == nil { + return false + } + cp := *old + cp.email = email + ib.clientsByID[id] = &cp + return true +} + +func (ib *nativeInbound) clientCount() int { + ib.clientMu.RLock() + defer ib.clientMu.RUnlock() + return len(ib.clientsByID) +} + +func (s *nativeXrayServer) addClient(inboundTag, uuid, email string) error { + s.mu.Lock() + ib := s.inboundsByTag[inboundTag] + running := s.running + s.mu.Unlock() + if !running || ib == nil { + return nil + } + return ib.addNativeClient(ib.protocol, uuid, email) +} + +func (s *nativeXrayServer) removeClient(inboundTag, uuid string) error { + s.mu.Lock() + ib := s.inboundsByTag[inboundTag] + running := s.running + s.mu.Unlock() + if !running || ib == nil { + return nil + } + ib.removeNativeClient(uuid) + return nil +} + +func (s *nativeXrayServer) updateClientEmail(uuid, email string) error { + s.mu.Lock() + inbounds := make([]*nativeInbound, 0, len(s.inboundsByTag)) + for _, ib := range s.inboundsByTag { + inbounds = append(inbounds, ib) + } + running := s.running + s.mu.Unlock() + if !running { + return nil + } + for _, ib := range inbounds { + ib.updateNativeClientEmail(uuid, email) + } + return nil +} + +func buildInboundTLS(in nativeInboundJSON) (*tls.Config, error) { + var certFile, keyFile string + if certs := in.StreamSettings.TLSSettings.Certificates; len(certs) > 0 { + certFile = certs[0].CertificateFile + keyFile = certs[0].KeyFile + } + if certFile == "" || keyFile == "" { + // Fall back to the panel's first TLS forwarder cert/key, which is the + // main TLS material an operator already configured for TLS-over-SSH. + if gc := getGlobalCfg(); gc != nil && len(gc.TLSForwarders) > 0 { + if certFile == "" { + certFile = gc.TLSForwarders[0].CertFile + } + if keyFile == "" { + keyFile = gc.TLSForwarders[0].KeyFile + } + } + } + if certFile == "" || keyFile == "" { + return nil, errors.New("no certificate/key configured") + } + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, err + } + return &tls.Config{ + Certificates: []tls.Certificate{cert}, + MinVersion: tls.VersionTLS12, + NextProtos: []string{"h2", "http/1.1"}, + }, nil +} + +// defaultNativeLimits converts the panel's default Mbps limits to bytes/sec. +func defaultNativeLimits() (up, down int) { + gc := getGlobalCfg() + if gc == nil { + return 0, 0 + } + return gc.DefaultLimitMbpsUp * 125000, gc.DefaultLimitMbpsDown * 125000 +} + +// parseSinglePort accepts an Xray port field that is a plain integer (the only +// form the panel generates) and returns it. Ranges/strings are rejected. +func parseSinglePort(raw json.RawMessage) (int, bool) { + if len(raw) == 0 { + return 0, false + } + var n int + if err := json.Unmarshal(raw, &n); err == nil && n > 0 && n < 65536 { + return n, true + } + var s string + if err := json.Unmarshal(raw, &s); err == nil { + if p, err := strconv.Atoi(strings.TrimSpace(s)); err == nil && p > 0 && p < 65536 { + return p, true + } + } + return 0, false +} + +// parseUUID parses a canonical 36-char UUID string into 16 bytes. +func parseUUID(s string) ([16]byte, error) { + var out [16]byte + clean := strings.ReplaceAll(strings.TrimSpace(s), "-", "") + if len(clean) != 32 { + return out, fmt.Errorf("expected 32 hex chars, got %d", len(clean)) + } + b, err := hex.DecodeString(clean) + if err != nil { + return out, err + } + copy(out[:], b) + return out, nil +} + +// normalizeNativeListenHost returns the host-only value expected by net.JoinHostPort. +// Xray's listen field is host-only, but panel/manual configs often store IPv6 in +// bracket form ("[2001:db8::1]") or accidentally store a full socket address +// ("[2001:db8::1]:443"). Passing a bracketed host to net.JoinHostPort creates +// invalid addresses like "[[2001:db8::1]]:443". Strip those forms here. +func normalizeNativeListenHost(raw string) string { + v := strings.TrimSpace(raw) + if v == "" { + return "0.0.0.0" + } + if h, _, err := net.SplitHostPort(v); err == nil { + v = strings.TrimSpace(h) + } + for len(v) >= 2 && strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") { + v = strings.TrimSpace(v[1 : len(v)-1]) + } + if v == "" { + return "0.0.0.0" + } + return v +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return v + } + } + return "" +} + +func orNone(s string) string { + if s == "" { + return "none" + } + return s +} diff --git a/xray_native_mux.go b/xray_native_mux.go new file mode 100644 index 0000000..2952e5e --- /dev/null +++ b/xray_native_mux.go @@ -0,0 +1,1123 @@ +package main + +import ( + "context" + "encoding/binary" + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/time/rate" +) + +const ( + nativeMuxStatusNew = 0x01 + nativeMuxStatusKeep = 0x02 + nativeMuxStatusEnd = 0x03 + nativeMuxStatusKeepAlive = 0x04 + + nativeMuxOptionData = 0x01 + nativeMuxOptionError = 0x02 + + nativeMuxNetworkTCP = 0x01 + nativeMuxNetworkUDP = 0x02 + + // Keep packet buffers below the kernel max. Mux packets are length-prefixed and + // capped at nativeUDPMaxPacket, so larger buffers only increase memory pressure. +) + +type nativeMuxMetadata struct { + sessionID uint16 + status byte + option byte + network byte + host string + port uint16 + globalID [8]byte +} + +type nativeMuxPacket struct { + payload []byte + host string + port uint16 + discard bool +} + +type nativeMuxUplinkItem struct { + payload []byte + host string + port uint16 +} + +const ( + nativeMuxUplinkQueue = 16 + nativeMuxMaxBufferedBytesPerSession = 1 * 1024 * 1024 + nativeMuxMaxBufferedBytesGlobal = 128 * 1024 * 1024 +) + +var nativeMuxFramePool = sync.Pool{ + New: func() any { + b := make([]byte, 0, 2+512+2+nativeUDPMaxPacket) + return &b + }, +} + +type nativeMuxSession struct { + id uint16 + network byte + xudp bool + + tcp net.Conn + udp net.PacketConn + + udpNetwork string + udpTarget net.Addr + + lastUDPHost string + lastUDPPort uint16 + lastUDPAddr net.Addr + + writeMu *sync.Mutex + client io.Writer + uuid string + email string + + upLimiter *rate.Limiter + downLimiter *rate.Limiter + upMeter *trafficMeter + downMeter *trafficMeter + + uplink chan nativeMuxUplinkItem + closed chan struct{} + closeOnce sync.Once + finishOnce sync.Once + enqueueMu sync.Mutex + enqueueWG sync.WaitGroup + enqueueDone bool + buffered atomic.Int64 + ctx context.Context + cancel context.CancelFunc + onClose func(*nativeMuxSession) + releaseSlot func() + globalID [8]byte +} + +var ( + nativeMuxGlobalActive atomic.Int64 + nativeMuxBufferedBytes atomic.Int64 + nativeMuxBufferRejected atomic.Int64 +) + +func acquireNativeMuxGlobalSlot() (func(), bool) { + limit := int64(nativeMuxGlobalSessionLimit()) + if limit <= 0 { + return func() {}, true + } + for { + cur := nativeMuxGlobalActive.Load() + if cur >= limit { + return nil, false + } + if nativeMuxGlobalActive.CompareAndSwap(cur, cur+1) { + var once sync.Once + return func() { once.Do(func() { nativeMuxGlobalActive.Add(-1) }) }, true + } + } +} + +func reserveNativeMuxBufferedBytes(s *nativeMuxSession, n int64) bool { + if s == nil || n <= 0 { + return true + } + for { + current := s.buffered.Load() + if current > nativeMuxMaxBufferedBytesPerSession-n { + logNativeLimitRejection("mux session buffered bytes", &nativeMuxBufferRejected, nativeMuxMaxBufferedBytesPerSession) + return false + } + if s.buffered.CompareAndSwap(current, current+n) { + break + } + } + for { + current := nativeMuxBufferedBytes.Load() + if current > nativeMuxMaxBufferedBytesGlobal-n { + s.buffered.Add(-n) + logNativeLimitRejection("mux global buffered bytes", &nativeMuxBufferRejected, nativeMuxMaxBufferedBytesGlobal) + return false + } + if nativeMuxBufferedBytes.CompareAndSwap(current, current+n) { + return true + } + } +} + +func releaseNativeMuxBufferedBytes(s *nativeMuxSession, n int64) { + if s == nil || n <= 0 { + return + } + for { + current := s.buffered.Load() + release := n + if release > current { + release = current + } + if s.buffered.CompareAndSwap(current, current-release) { + releaseNativeAtomicBytes(&nativeMuxBufferedBytes, release) + return + } + } +} + +func releaseNativeAtomicBytes(counter *atomic.Int64, n int64) { + if counter == nil || n <= 0 { + return + } + for { + current := counter.Load() + next := current - n + if next < 0 { + next = 0 + } + if counter.CompareAndSwap(current, next) { + return + } + } +} + +// nativeVLESSMuxTunnel implements the server side of Xray's Mux.Cool framing +// for VLESS CommandMux. CommandMux does not carry a VLESS target address; every +// child TCP/UDP request is described by mux frame metadata. UDP is treated as a +// packet protocol, not as a byte stream, and XUDP-style GlobalID/endpoint +// metadata is accepted for full-cone friendly clients. +func (ib *nativeInbound) nativeVLESSMuxTunnel(stream io.ReadWriteCloser, uuid, email string, quotaState *xrayNativeQuotaState) { + defer xrayRecover(fmt.Sprintf("native xray VLESS mux user=%s", email)) + + writeMu := &sync.Mutex{} + sessions := make(map[uint16]*nativeMuxSession) + xudpSessions := make(map[[8]byte]*nativeMuxSession) + readScratch := make([]byte, 0, nativeUDPMaxPacket) + var mu sync.Mutex + + removeSession := func(s *nativeMuxSession) { + if s == nil { + return + } + mu.Lock() + if cur := sessions[s.id]; cur == s { + delete(sessions, s.id) + } + if s.xudp && s.globalID != [8]byte{} { + if cur := xudpSessions[s.globalID]; cur == s { + delete(xudpSessions, s.globalID) + } + } + mu.Unlock() + } + + closeSession := func(id uint16) { + mu.Lock() + s := sessions[id] + if s != nil { + delete(sessions, id) + if s.xudp && s.globalID != [8]byte{} { + delete(xudpSessions, s.globalID) + } + } + mu.Unlock() + if s != nil { + s.closeBackend() + } + } + + defer func() { + mu.Lock() + all := make([]*nativeMuxSession, 0, len(sessions)) + for _, s := range sessions { + all = append(all, s) + } + sessions = make(map[uint16]*nativeMuxSession) + xudpSessions = make(map[[8]byte]*nativeMuxSession) + mu.Unlock() + for _, s := range all { + s.closeBackend() + } + _ = stream.Close() + }() + + for { + meta, err := readNativeMuxMetadata(stream) + if err != nil { + if err != io.EOF { + xrayLogf("native xray: VLESS mux metadata read failed: %v", err) + } + return + } + + switch meta.status { + case nativeMuxStatusKeepAlive: + if meta.option&nativeMuxOptionData != 0 { + _, readScratch, _ = readNativeMuxDataBlockScratch(stream, readScratch) + } + + case nativeMuxStatusEnd: + if meta.option&nativeMuxOptionData != 0 { + _, readScratch, _ = readNativeMuxDataBlockScratch(stream, readScratch) + } + closeSession(meta.sessionID) + + case nativeMuxStatusNew: + if meta.network != nativeMuxNetworkTCP && meta.network != nativeMuxNetworkUDP { + xrayLogf("native xray: VLESS mux session %d unsupported network %d", meta.sessionID, meta.network) + if meta.option&nativeMuxOptionData != 0 { + _, readScratch, _ = readNativeMuxDataBlockScratch(stream, readScratch) + } + continue + } + + mu.Lock() + tooManySessions := len(sessions) >= nativeMuxMaxSessionLimit() + mu.Unlock() + if tooManySessions { + if meta.option&nativeMuxOptionData != 0 { + _ = discardNativeMuxDataBlock(stream) + } + xrayTracef("native xray: VLESS mux rejected new session=%d over limit=%d user=%s", meta.sessionID, nativeMuxMaxSessionLimit(), email) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, true) + writeMu.Unlock() + continue + } + + isXUDP := meta.globalID != [8]byte{} + pkt := nativeMuxPacket{} + + targetHost, targetPort := meta.host, meta.port + if isNativeDNSSinkTarget(targetHost) { + if meta.option&nativeMuxOptionData != 0 { + _ = discardNativeMuxDataBlock(stream) + } + xrayTracef("native xray: VLESS mux fast-ignored DNS sink target session=%d network=%s host=%q port=%d xudp=%v", meta.sessionID, nativeMuxNetworkName(meta.network), targetHost, targetPort, isXUDP) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, false) + writeMu.Unlock() + continue + } + if invalidNativeDestination(targetHost, targetPort) { + if meta.option&nativeMuxOptionData != 0 { + _ = discardNativeMuxDataBlock(stream) + } + xrayTracef("native xray: VLESS mux rejected invalid target session=%d network=%s host=%q port=%d xudp=%v", meta.sessionID, nativeMuxNetworkName(meta.network), targetHost, targetPort, isXUDP) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, true) + writeMu.Unlock() + continue + } + + if meta.option&nativeMuxOptionData != 0 { + pkt.payload, readScratch, err = readNativeMuxDataBlockScratch(stream, readScratch) + if err != nil { + xrayLogf("native xray: VLESS mux first packet read failed session=%d: %v", meta.sessionID, err) + continue + } + } + + s, target, err := ib.newNativeMuxSession(meta.sessionID, meta.network, targetHost, targetPort, isXUDP, meta.globalID, stream, writeMu, uuid, email, quotaState, removeSession) + if err != nil { + xrayLogf("native xray: VLESS mux session %s setup failed: %v", target, err) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, true) + writeMu.Unlock() + continue + } + + mu.Lock() + if old := sessions[meta.sessionID]; old != nil { + old.closeBackend() + } + sessions[meta.sessionID] = s + if isXUDP { + if old := xudpSessions[meta.globalID]; old != nil && old != s { + old.closeBackend() + } + xudpSessions[meta.globalID] = s + } + mu.Unlock() + + xrayTracef("native xray: vless/mux %s user=%s -> %s session=%d xudp=%v", nativeMuxNetworkName(meta.network), email, target, meta.sessionID, isXUDP) + ib2, host2, port2 := ib, targetHost, targetPort + xrayGo(fmt.Sprintf("native xray mux session=%d", s.id), func() { s.run(ib2, host2, port2) }) + if len(pkt.payload) > 0 && !s.enqueueUplink(pkt.payload, pkt.host, pkt.port) { + closeSession(s.id) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, true) + writeMu.Unlock() + } + + case nativeMuxStatusKeep: + mu.Lock() + s := sessions[meta.sessionID] + if s == nil && meta.globalID != [8]byte{} { + s = xudpSessions[meta.globalID] + } + mu.Unlock() + if meta.option&nativeMuxOptionData == 0 { + continue + } + pkt := nativeMuxPacket{} + pkt.payload, readScratch, err = readNativeMuxDataBlockScratch(stream, readScratch) + if err != nil { + xrayLogf("native xray: VLESS mux keep packet read failed session=%d: %v", meta.sessionID, err) + if s != nil { + closeSession(s.id) + } + continue + } + if s == nil { + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, false) + writeMu.Unlock() + continue + } + // Official Mux.Cool packet sessions read exactly one packet block here. + // XUDP is represented by GlobalID on the New frame and optional UDP + // endpoint metadata on Keep frames, not by auto-detecting metadata inside + // the UDP payload. Auto-detecting inside payload can block QUIC if a real + // datagram happens to look like XUDP control bytes. + if meta.host != "" { + pkt.host = meta.host + pkt.port = meta.port + } + if len(pkt.payload) > 0 && !s.enqueueUplink(pkt.payload, pkt.host, pkt.port) { + closeSession(s.id) + writeMu.Lock() + _ = writeNativeMuxEnd(stream, meta.sessionID, true) + writeMu.Unlock() + } + + default: + xrayLogf("native xray: VLESS mux unknown status %d", meta.status) + if meta.option&nativeMuxOptionData != 0 { + _, readScratch, _ = readNativeMuxDataBlockScratch(stream, readScratch) + } + } + } +} + +func (ib *nativeInbound) newNativeMuxSession(id uint16, network byte, host string, port uint16, xudp bool, globalID [8]byte, client io.Writer, writeMu *sync.Mutex, uuid, email string, quotaState *xrayNativeQuotaState, onClose func(*nativeMuxSession)) (*nativeMuxSession, string, error) { + target := net.JoinHostPort(normalizeNativeTargetHost(host), strconv.Itoa(int(port))) + if invalidNativeDestination(host, port) { + return nil, target, fmt.Errorf("invalid destination") + } + releaseSlot, ok := acquireNativeMuxGlobalSlot() + if !ok { + return nil, target, fmt.Errorf("global mux session limit reached") + } + s := &nativeMuxSession{ + id: id, + network: network, + xudp: xudp, + writeMu: writeMu, + client: client, + uuid: uuid, + email: email, + upLimiter: ib.upLimiter(), + downLimiter: ib.downLimiter(), + upMeter: newTrafficMeter(uuid, email, true, quotaState), + downMeter: newTrafficMeter(uuid, email, false, quotaState), + uplink: make(chan nativeMuxUplinkItem, nativeMuxUplinkQueue), + closed: make(chan struct{}), + onClose: onClose, + releaseSlot: releaseSlot, + globalID: globalID, + } + s.ctx, s.cancel = context.WithCancel(context.Background()) + return s, target, nil +} + +func (s *nativeMuxSession) run(ib *nativeInbound, host string, port uint16) { + defer xrayRecover(fmt.Sprintf("native xray mux run session=%d", s.id)) + defer s.finish() + + select { + case <-s.closed: + s.failInit(false) + return + default: + } + + if s.network == nativeMuxNetworkTCP { + backend, target, err := ib.nativeDialTCP(host, port) + if err != nil { + xrayLogf("native xray: VLESS mux TCP dial %s failed session=%d: %v", target, s.id, err) + s.failInit(true) + return + } + s.tcp = backend + } else { + pc, udpNetwork, udpTarget, target, err := ib.nativeOpenMuxUDP(host, port) + if err != nil { + xrayLogf("native xray: VLESS mux UDP open %s failed session=%d: %v", target, s.id, err) + s.failInit(true) + return + } + s.udp = pc + s.udpNetwork = udpNetwork + s.udpTarget = udpTarget + } + + select { + case <-s.closed: + s.closeBackend() + return + default: + } + + xrayGo(fmt.Sprintf("native xray mux backend session=%d", s.id), func() { s.readBackendLoop() }) + s.uplinkLoop() +} + +func (s *nativeMuxSession) failInit(notifyClient bool) { + if notifyClient { + s.writeMu.Lock() + _ = writeNativeMuxEnd(s.client, s.id, true) + s.writeMu.Unlock() + } + s.finish() +} + +// finish is the single lifecycle exit for a mux child. The backend reader, +// uplink loop, parent mux stream, and initialization path can all detect the +// terminal condition concurrently, so both cleanup and map removal must be +// exactly-once operations. +func (s *nativeMuxSession) finish() { + s.finishOnce.Do(func() { + s.closeBackend() + if s.onClose != nil { + s.onClose(s) + } + }) +} + +func (s *nativeMuxSession) beginEnqueue() bool { + s.enqueueMu.Lock() + defer s.enqueueMu.Unlock() + if s.enqueueDone { + return false + } + s.enqueueWG.Add(1) + return true +} + +func (s *nativeMuxSession) enqueueUplink(payload []byte, host string, port uint16) bool { + if len(payload) == 0 { + return true + } + if !s.beginEnqueue() { + return false + } + defer s.enqueueWG.Done() + + bytes := int64(len(payload)) + if !reserveNativeMuxBufferedBytes(s, bytes) { + return false + } + cp := make([]byte, len(payload)) + copy(cp, payload) + select { + case s.uplink <- nativeMuxUplinkItem{payload: cp, host: host, port: port}: + return true + case <-s.closed: + releaseNativeMuxBufferedBytes(s, bytes) + return false + } +} + +func (s *nativeMuxSession) processUplinkItem(item nativeMuxUplinkItem) bool { + defer releaseNativeMuxBufferedBytes(s, int64(len(item.payload))) + return s.writeBackendItem(item) +} + +func (s *nativeMuxSession) uplinkLoop() { + defer s.upMeter.flush() + for { + select { + case <-s.closed: + return + case item := <-s.uplink: + if !s.processUplinkItem(item) { + s.closeBackend() + return + } + } + } +} + +func (ib *nativeInbound) nativeOpenMuxUDP(host string, port uint16) (net.PacketConn, string, net.Addr, string, error) { + targetHost := normalizeNativeTargetHost(host) + target := net.JoinHostPort(targetHost, strconv.Itoa(int(port))) + udpNetwork := nativeDialNetwork("udp", targetHost) + udpTarget, err := net.ResolveUDPAddr(udpNetwork, target) + if err != nil { + return nil, udpNetwork, nil, target, err + } + + var local *net.UDPAddr + if addr := nativeLocalAddrForDial(udpNetwork, targetHost, ib.listen); addr != nil { + if udpAddr, ok := addr.(*net.UDPAddr); ok { + local = udpAddr + } + } + pc, err := net.ListenUDP(udpNetwork, local) + if err != nil { + return nil, udpNetwork, nil, target, err + } + if nativeMuxUDPReadBufferSize() > 0 { + _ = pc.SetReadBuffer(nativeMuxUDPReadBufferSize()) + } + if nativeMuxUDPWriteBufferSize() > 0 { + _ = pc.SetWriteBuffer(nativeMuxUDPWriteBufferSize()) + } + return pc, udpNetwork, udpTarget, target, nil +} + +func (s *nativeMuxSession) writeBackendItem(item nativeMuxUplinkItem) bool { + payload := item.payload + if len(payload) == 0 { + return true + } + if s.upLimiter != nil { + if err := s.upLimiter.WaitN(s.ctx, len(payload)); err != nil { + return false + } + } + quotaReservation, quotaErr := reserveNativePacketQuota(s.upMeter, len(payload)) + if quotaErr != nil { + return false + } + if err := quotaReservation.wait(s.ctx); err != nil { + return false + } + + var n int + var err error + if s.network == nativeMuxNetworkTCP { + n, err = s.tcp.Write(payload) + } else { + target := s.udpTarget + if item.host != "" && item.port != 0 { + if isNativeDNSSinkTarget(item.host) || invalidNativeDestination(item.host, item.port) { + // AdGuard/blocked endpoints must be ignored at the cheapest possible + // point. Do not resolve, dial, log loudly, or keep the mux child busy. + quotaReservation.finish(0) + xrayTracef("native xray: VLESS mux UDP fast-ignored override sink session=%d target=%s:%d", s.id, item.host, item.port) + return true + } + if s.lastUDPAddr != nil && s.lastUDPHost == item.host && s.lastUDPPort == item.port { + target = s.lastUDPAddr + } else if addr, rerr := resolveNativeMuxUDPAddr(s.udpNetwork, item.host, item.port); rerr == nil { + target = addr + s.lastUDPHost = item.host + s.lastUDPPort = item.port + s.lastUDPAddr = addr + } else { + quotaReservation.finish(0) + xrayTracef("native xray: VLESS mux UDP override resolve failed session=%d target=%s:%d: %v", s.id, item.host, item.port, rerr) + return true + } + } + n, err = s.udp.WriteTo(payload, target) + } + if s.network == nativeMuxNetworkUDP && err == nil { + _ = s.udp.SetReadDeadline(time.Now().Add(nativeMuxUDPIdleTimeout())) + } + quotaReservation.finish(n) + if err != nil { + xrayLogf("native xray: VLESS mux backend write failed session=%d: %v", s.id, err) + return false + } + return true +} + +func (s *nativeMuxSession) readBackendLoop() { + defer xrayRecover(fmt.Sprintf("native xray mux backend loop session=%d", s.id)) + sendEnd := true + defer func() { + s.downMeter.flush() + if sendEnd { + s.writeMu.Lock() + _ = writeNativeMuxEnd(s.client, s.id, false) + s.writeMu.Unlock() + } + s.finish() + }() + + if s.network == nativeMuxNetworkTCP { + s.readTCPBackendLoop() + return + } + // For UDP/QUIC, an idle backend timeout is only local cleanup. Sending an + // End frame on idle makes some clients close the whole video/QUIC flow after + // a short quiet period. Real errors still return true and notify the client. + sendEnd = s.readUDPBackendLoop() +} + +func (s *nativeMuxSession) waitDownRate(n int) error { + if s.downLimiter == nil || n <= 0 { + return nil + } + return s.downLimiter.WaitN(s.ctx, n) +} + +func (s *nativeMuxSession) readTCPBackendLoop() { + buf := make([]byte, 16*1024) + for { + n, err := s.tcp.Read(buf) + if err != nil { + if err != io.EOF { + xrayLogf("native xray: VLESS mux TCP backend read failed session=%d: %v", s.id, err) + } + return + } + if n <= 0 { + continue + } + if err := s.waitDownRate(n); err != nil { + return + } + quotaReservation, quotaErr := reserveNativePacketQuota(s.downMeter, n) + if quotaErr != nil { + return + } + if err := quotaReservation.wait(s.ctx); err != nil { + return + } + s.writeMu.Lock() + werr := writeNativeMuxData(s.client, s.id, nativeMuxStatusKeep, buf[:n]) + s.writeMu.Unlock() + if werr != nil { + quotaReservation.finish(0) + xrayLogf("native xray: VLESS mux TCP client write failed session=%d: %v", s.id, werr) + return + } + quotaReservation.finish(n) + } +} + +func (s *nativeMuxSession) readUDPBackendLoop() bool { + buf := make([]byte, nativeUDPBufferSize) + for { + _ = s.udp.SetReadDeadline(time.Now().Add(nativeMuxUDPIdleTimeout())) + n, addr, err := s.udp.ReadFrom(buf) + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Timeout() { + return false + } + if err != io.EOF { + xrayLogf("native xray: VLESS mux UDP backend read failed session=%d: %v", s.id, err) + } + return true + } + if n <= 0 { + continue + } + if err := s.waitDownRate(n); err != nil { + return true + } + quotaReservation, quotaErr := reserveNativePacketQuota(s.downMeter, n) + if quotaErr != nil { + return true + } + if err := quotaReservation.wait(s.ctx); err != nil { + return true + } + s.writeMu.Lock() + // Include the UDP source endpoint on XUDP responses so clients that rely on + // full-cone packet addressing can associate the datagram with the correct + // origin. Classic mux UDP also accepts this optional metadata in Xray. + werr := writeNativeMuxPacketData(s.client, s.id, nativeMuxStatusKeep, buf[:n], addr, s.xudp) + s.writeMu.Unlock() + if werr != nil { + quotaReservation.finish(0) + xrayLogf("native xray: VLESS mux UDP client write failed session=%d: %v", s.id, werr) + return true + } + quotaReservation.finish(n) + } +} + +func (s *nativeMuxSession) closeBackend() { + s.closeOnce.Do(func() { + s.enqueueMu.Lock() + s.enqueueDone = true + close(s.closed) + s.enqueueMu.Unlock() + if s.cancel != nil { + s.cancel() + } + if s.tcp != nil { + _ = s.tcp.Close() + } + if s.udp != nil { + _ = s.udp.Close() + } + + // Wait for producers that passed beginEnqueue before the close flag, then + // discard any payloads the consumer did not take. This returns every byte + // reservation even when shutdown races a full queue. + s.enqueueWG.Wait() + for { + select { + case item := <-s.uplink: + releaseNativeMuxBufferedBytes(s, int64(len(item.payload))) + item.payload = nil + default: + if s.releaseSlot != nil { + s.releaseSlot() + } + return + } + } + }) +} + +func nativeMuxNetworkName(network byte) string { + if network == nativeMuxNetworkUDP { + return "udp" + } + return "tcp" +} + +func readNativeMuxMetadata(r io.Reader) (nativeMuxMetadata, error) { + var meta nativeMuxMetadata + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return meta, err + } + metaLen := int(binary.BigEndian.Uint16(lenBuf[:])) + if metaLen < 4 || metaLen > 512 { + return meta, fmt.Errorf("invalid mux metadata length %d", metaLen) + } + var stack [512]byte + b := stack[:metaLen] + if _, err := io.ReadFull(r, b); err != nil { + return meta, err + } + meta.sessionID = binary.BigEndian.Uint16(b[0:2]) + meta.status = b[2] + meta.option = b[3] + off := 4 + if meta.status == nativeMuxStatusNew { + if off >= len(b) { + return meta, fmt.Errorf("mux new frame missing network") + } + meta.network = b[off] + off++ + host, port, next, err := parseNativeMuxAddressPort(b, off) + if err != nil { + return meta, err + } + meta.host, meta.port, off = host, port, next + } else if meta.status == nativeMuxStatusKeep && off < len(b) && b[off] == nativeMuxNetworkUDP { + meta.network = b[off] + off++ + host, port, next, err := parseNativeMuxAddressPort(b, off) + if err == nil { + meta.host, meta.port, off = host, port, next + } + } + if meta.status == nativeMuxStatusNew && meta.network == nativeMuxNetworkUDP && meta.option&nativeMuxOptionData != 0 && len(b)-off >= 8 { + copy(meta.globalID[:], b[len(b)-8:]) + } + return meta, nil +} + +func parseNativeMuxAddressPort(b []byte, off int) (string, uint16, int, error) { + if off+3 > len(b) { + return "", 0, off, io.ErrUnexpectedEOF + } + port := binary.BigEndian.Uint16(b[off : off+2]) + off += 2 + atyp := b[off] + off++ + switch atyp { + case atypIPv4: + if off+4 > len(b) { + return "", 0, off, io.ErrUnexpectedEOF + } + host := net.IP(b[off : off+4]).String() + return host, port, off + 4, nil + case atypIPv6: + if off+16 > len(b) { + return "", 0, off, io.ErrUnexpectedEOF + } + host := net.IP(b[off : off+16]).String() + return host, port, off + 16, nil + case atypDomain: + if off >= len(b) { + return "", 0, off, io.ErrUnexpectedEOF + } + l := int(b[off]) + off++ + if off+l > len(b) { + return "", 0, off, io.ErrUnexpectedEOF + } + return string(b[off : off+l]), port, off + l, nil + default: + return "", 0, off, fmt.Errorf("unknown mux address type %d", atyp) + } +} + +func appendNativeMuxAddressPort(dst []byte, host string, port uint16) []byte { + var p [2]byte + binary.BigEndian.PutUint16(p[:], port) + dst = append(dst, p[:]...) + ip := net.ParseIP(stripNativeIPZone(normalizeNativeTargetHost(host))) + if ip4 := ip.To4(); ip4 != nil { + dst = append(dst, atypIPv4) + dst = append(dst, ip4...) + return dst + } + if ip16 := ip.To16(); ip16 != nil { + dst = append(dst, atypIPv6) + dst = append(dst, ip16...) + return dst + } + if len(host) > 255 { + host = host[:255] + } + dst = append(dst, atypDomain, byte(len(host))) + dst = append(dst, []byte(host)...) + return dst +} + +func readNativeMuxDataBlock(r io.Reader) ([]byte, error) { + payload, _, err := readNativeMuxDataBlockScratch(r, nil) + return payload, err +} + +func readNativeMuxDataBlockScratch(r io.Reader, scratch []byte) ([]byte, []byte, error) { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, scratch, err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n > nativeUDPMaxPacket { + return nil, scratch, fmt.Errorf("mux payload too large: %d", n) + } + if cap(scratch) < n { + scratch = make([]byte, n) + } + payload := scratch[:n] + _, err := io.ReadFull(r, payload) + return payload, scratch, err +} + +func discardNativeMuxDataBlock(r io.Reader) error { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n > nativeUDPMaxPacket { + return fmt.Errorf("mux payload too large: %d", n) + } + _, err := io.CopyN(io.Discard, r, int64(n)) + return err +} + +func readNativeMuxPacket(r io.Reader, allowXUDP bool) (nativeMuxPacket, error) { + var pkt nativeMuxPacket + for { + block, err := readNativeMuxDataBlock(r) + if err != nil { + return pkt, err + } + if !allowXUDP || !isNativeXUDPMetadata(block) { + pkt.payload = block + return pkt, nil + } + inner, err := parseNativeXUDPMetadata(block) + if err != nil { + return pkt, err + } + if inner.discard { + return inner, nil + } + if block[3]&1 == 0 { + continue + } + inner.payload, err = readNativeMuxDataBlock(r) + if err != nil { + return pkt, err + } + return inner, nil + } +} + +func appendUint16(dst []byte, v uint16) []byte { + return append(dst, byte(v>>8), byte(v)) +} + +func writeNativeMuxData(w io.Writer, sessionID uint16, status byte, payload []byte) error { + return writeNativeMuxPacketData(w, sessionID, status, payload, nil, false) +} + +func writeNativeMuxPacketData(w io.Writer, sessionID uint16, status byte, payload []byte, udpAddr net.Addr, includeUDPAddr bool) error { + if len(payload) > nativeUDPMaxPacket { + return fmt.Errorf("mux payload too large: %d", len(payload)) + } + bufp := nativeMuxFramePool.Get().(*[]byte) + frame := (*bufp)[:0] + frame = append(frame, 0, 0) // metadata length placeholder + metaStart := len(frame) + frame = append(frame, byte(sessionID>>8), byte(sessionID), status, nativeMuxOptionData) + if includeUDPAddr && udpAddr != nil { + if host, port, ok := nativeMuxAddrHostPort(udpAddr); ok { + frame = append(frame, nativeMuxNetworkUDP) + frame = appendNativeMuxAddressPort(frame, host, port) + } + } + metaLen := len(frame) - metaStart + binary.BigEndian.PutUint16(frame[:2], uint16(metaLen)) + frame = appendUint16(frame, uint16(len(payload))) + frame = append(frame, payload...) + _, err := w.Write(frame) + *bufp = frame[:0] + nativeMuxFramePool.Put(bufp) + return err +} + +func writeNativeMuxEnd(w io.Writer, sessionID uint16, hasError bool) error { + opt := byte(0) + if hasError { + opt = nativeMuxOptionError + } + var frame [6]byte + binary.BigEndian.PutUint16(frame[0:2], 4) + binary.BigEndian.PutUint16(frame[2:4], sessionID) + frame[4] = nativeMuxStatusEnd + frame[5] = opt + _, err := w.Write(frame[:]) + return err +} + +func isNativeXUDPMetadata(meta []byte) bool { + if len(meta) < 4 || len(meta) > 512 { + return false + } + // Xray's xudp.PacketWriter stores a two-byte mux session id at the start of + // the inner metadata. For client-generated packets this is normally zero. + if meta[0] != 0 || meta[1] != 0 { + return false + } + cmd := meta[2] + opt := meta[3] + if cmd != 1 && cmd != 2 && cmd != 4 { + return false + } + if opt != 0 && opt != 1 { + return false + } + if len(meta) == 4 { + return true + } + return meta[4] == nativeMuxNetworkUDP +} + +func parseNativeXUDPMetadata(meta []byte) (nativeMuxPacket, error) { + var pkt nativeMuxPacket + if !isNativeXUDPMetadata(meta) { + return pkt, fmt.Errorf("invalid xudp metadata") + } + cmd := meta[2] + opt := meta[3] + if cmd == 4 { + pkt.discard = true + return pkt, nil + } + if len(meta) > 4 && meta[4] == nativeMuxNetworkUDP { + host, port, _, err := parseNativeMuxAddressPort(meta, 5) + if err != nil { + return pkt, err + } + pkt.host = host + pkt.port = port + } + if opt&1 == 0 { + return pkt, nil + } + // Payload length and bytes follow in the outer stream, so the caller must + // fill pkt.payload. This path is only used by readNativeXUDPPacket below. + return pkt, nil +} + +func readNativeXUDPPacket(r io.Reader) (nativeMuxPacket, error) { + var pkt nativeMuxPacket + for { + meta, err := readNativeMuxDataBlock(r) + if err != nil { + return pkt, err + } + pkt, err = parseNativeXUDPMetadata(meta) + if err != nil { + return pkt, err + } + if pkt.discard { + return pkt, nil + } + if meta[3]&1 == 0 { + continue + } + payload, err := readNativeMuxDataBlock(r) + if err != nil { + return pkt, err + } + pkt.payload = payload + return pkt, nil + } +} + +func resolveNativeMuxUDPAddr(network, host string, port uint16) (net.Addr, error) { + targetHost := normalizeNativeTargetHost(host) + if network == "" { + network = nativeDialNetwork("udp", targetHost) + } + return net.ResolveUDPAddr(network, net.JoinHostPort(targetHost, strconv.Itoa(int(port)))) +} + +func nativeMuxAddrHostPort(addr net.Addr) (string, uint16, bool) { + switch a := addr.(type) { + case *net.UDPAddr: + if a == nil { + return "", 0, false + } + return a.IP.String(), uint16(a.Port), true + case *net.TCPAddr: + if a == nil { + return "", 0, false + } + return a.IP.String(), uint16(a.Port), true + } + host, portStr, err := net.SplitHostPort(addr.String()) + if err != nil { + return "", 0, false + } + port64, err := strconv.ParseUint(portStr, 10, 16) + if err != nil { + return "", 0, false + } + return stripNativeIPZone(host), uint16(port64), true +} + +func stripNativeIPZone(host string) string { + if i := strings.LastIndexByte(host, '%'); i >= 0 { + return host[:i] + } + return host +} diff --git a/xray_native_safety.go b/xray_native_safety.go new file mode 100644 index 0000000..fa3f20c --- /dev/null +++ b/xray_native_safety.go @@ -0,0 +1,276 @@ +package main + +import ( + "net" + "runtime/debug" + "sync" + "sync/atomic" + "time" +) + +const nativeOverloadBackoff = 10 * time.Millisecond + +// xrayRecover prevents a bad client packet, closed HTTP stream, or mux/session +// race from taking down the whole sshpanel process. A panic should only kill the +// current native Xray connection/session and must always leave a visible stack +// trace in /api/xray/logs and journald. +func xrayRecover(where string) { + if r := recover(); r != nil { + xrayLogf("native xray: panic recovered in %s: %v\n%s", where, r, debug.Stack()) + } +} + +func xrayGo(where string, fn func()) { + go func() { + defer xrayRecover(where) + fn() + }() +} + +func init() { + // Direct native-inbound tests and embedders may run an accept loop without + // the singleton server start method. Production stop() flips this to false. + nativeTransportAccepting.Store(true) +} + +var ( + nativeTransportConnections atomic.Int64 + nativeXHTTPSessions atomic.Int64 + nativeXHTTPRequests atomic.Int64 + nativeClientConnsRejected atomic.Int64 + nativePreAuthRejected atomic.Int64 + nativeXHTTPRejected atomic.Int64 + + nativeTransportAccepting atomic.Bool + nativeTransportRegistry = struct { + sync.Mutex + conns map[*nativeCountedConn]struct{} + }{conns: make(map[*nativeCountedConn]struct{})} +) + +// acquireNativeCounter tracks a counted resource and returns an exactly-once +// release function. Limits here are simultaneous resource-safety windows, not +// traffic-volume or request-rate ceilings. +func acquireNativeCounter(active *atomic.Int64, limit int) (func(), bool) { + for { + current := active.Load() + if limit > 0 && current >= int64(limit) { + return nil, false + } + if active.CompareAndSwap(current, current+1) { + var once sync.Once + return func() { + once.Do(func() { + if active.Add(-1) < 0 { + active.Store(0) + } + }) + }, true + } + } +} + +func shouldLogNativeSample(counter *atomic.Int64) (n int64, ok bool) { + n = counter.Add(1) + // Keep attacks visible without allowing logging itself to become a CPU/disk + // amplifier. The first event and one event per 1024 repetitions are logged. + return n, n == 1 || n%1024 == 0 +} + +func logNativeLimitRejection(kind string, rejected *atomic.Int64, limit int) { + n, ok := shouldLogNativeSample(rejected) + if ok { + xrayLogf("native xray: rejected %s at safety limit=%d (rejected=%d)", kind, limit, n) + } +} + +func logNativeClientLimitRejection(email string, limit int) { + n, ok := shouldLogNativeSample(&nativeClientConnsRejected) + if ok { + xrayLogf("native xray: rejected authenticated user %s at max_conns=%d (rejected=%d)", email, limit, n) + } +} + +func logNativePreAuthRejection(format string, args ...interface{}) { + if _, ok := shouldLogNativeSample(&nativePreAuthRejected); ok { + xrayLogf(format, args...) + } +} + +func acquireNativeTransportConnection() (func(), bool) { + return acquireNativeCounter(&nativeTransportConnections, nativeTransportConnectionLimit()) +} + +func acquireNativeXHTTPSession() (func(), bool) { + return acquireNativeCounter(&nativeXHTTPSessions, nativeXHTTPSessionLimit()) +} + +func acquireNativeXHTTPRequest() (func(), bool) { + return acquireNativeCounter(&nativeXHTTPRequests, nativeXHTTPRequestLimit()) +} + +func configureNativeTransportSocket(c net.Conn) { + if tc, ok := c.(*net.TCPConn); ok { + _ = tc.SetKeepAlive(true) + _ = tc.SetKeepAlivePeriod(30 * time.Second) + _ = tc.SetNoDelay(true) + } +} + +// nativeCountedConn releases its global transport slot and unregisters itself +// exactly once, even when several tunnel paths race to close the same socket. +type nativeCountedConn struct { + net.Conn + release func() + onClose func() + closeOnce sync.Once + closeErr error +} + +func (c *nativeCountedConn) Close() error { + c.closeOnce.Do(func() { + c.closeErr = c.Conn.Close() + if c.release != nil { + c.release() + } + if c.onClose != nil { + c.onClose() + } + }) + return c.closeErr +} + +// wrapNativeTransportConn applies only the global counter. It is useful for +// focused tests and for callers that own connection lifetime themselves. +func wrapNativeTransportConn(c net.Conn) (net.Conn, bool) { + if c == nil { + return nil, false + } + configureNativeTransportSocket(c) + release, ok := acquireNativeTransportConnection() + if !ok { + _ = c.Close() + return nil, false + } + return &nativeCountedConn{Conn: c, release: release}, true +} + +// wrapTrackedNativeTransportConn additionally registers the accepted socket so +// stopping/restarting native Xray closes established raw, WebSocket, TLS, HTTP/1 +// and HTTP/2 transports instead of leaving tunnel goroutines alive. +func wrapTrackedNativeTransportConn(c net.Conn) (net.Conn, bool) { + if c == nil { + return nil, false + } + configureNativeTransportSocket(c) + if !nativeTransportAccepting.Load() { + _ = c.Close() + return nil, false + } + release, ok := acquireNativeTransportConnection() + if !ok { + _ = c.Close() + return nil, false + } + return registerTrackedNativeTransportConn(c, release) +} + +// registerTrackedNativeTransportConn finishes registration when the caller has +// already reserved a transport slot. Keeping reservation and Accept separate is +// what lets the production listener apply kernel/socket backpressure instead of +// accepting and immediately resetting connections at capacity. +func registerTrackedNativeTransportConn(c net.Conn, release func()) (net.Conn, bool) { + counted := &nativeCountedConn{Conn: c, release: release} + counted.onClose = func() { + nativeTransportRegistry.Lock() + delete(nativeTransportRegistry.conns, counted) + nativeTransportRegistry.Unlock() + } + + nativeTransportRegistry.Lock() + if !nativeTransportAccepting.Load() { + nativeTransportRegistry.Unlock() + _ = counted.Close() + return nil, false + } + nativeTransportRegistry.conns[counted] = struct{}{} + nativeTransportRegistry.Unlock() + return counted, true +} + +// waitWrapTrackedNativeTransportConn is used by raw native accept loops. Waiting +// here, before another connection is admitted to the protocol handler, applies +// socket/kernel backpressure instead of creating an unbounded goroutine backlog. +func waitWrapTrackedNativeTransportConn(c net.Conn) (net.Conn, bool) { + if c == nil { + return nil, false + } + configureNativeTransportSocket(c) + for nativeTransportAccepting.Load() { + release, ok := acquireNativeTransportConnection() + if ok { + return registerTrackedNativeTransportConn(c, release) + } + time.Sleep(nativeOverloadBackoff) + } + _ = c.Close() + return nil, false +} + +func beginNativeTransportAccepting() { + nativeTransportAccepting.Store(true) +} + +func stopNativeTransportAccepting() { + nativeTransportAccepting.Store(false) +} + +func closeAllNativeTransportConnections() { + nativeTransportRegistry.Lock() + conns := make([]*nativeCountedConn, 0, len(nativeTransportRegistry.conns)) + for c := range nativeTransportRegistry.conns { + conns = append(conns, c) + } + nativeTransportRegistry.Unlock() + for _, c := range conns { + _ = c.Close() + } +} + +// nativeTrackingListener registers every accepted XHTTP socket so a live +// stop/reload can close it. It reserves capacity before Accept so overload stays +// in the kernel accept queue rather than allocating more Go handlers. +type nativeTrackingListener struct { + net.Listener +} + +func (l nativeTrackingListener) Accept() (net.Conn, error) { + for { + release, ok := acquireNativeTransportConnection() + if !ok { + // Unlimited admission can only fail if this implementation changes. Avoid + // accepting and resetting a socket if that ever happens. + time.Sleep(nativeOverloadBackoff) + continue + } + c, err := l.Listener.Accept() + if err != nil { + release() + return nil, err + } + configureNativeTransportSocket(c) + if counted, ok := registerTrackedNativeTransportConn(c, release); ok { + return counted, nil + } + // Shutdown may race Accept. Registration closes the socket and releases the + // slot; the next Accept observes the listener close. + time.Sleep(nativeOverloadBackoff) + } +} + +func trackNativeListener(ln net.Listener) net.Listener { + if ln == nil { + return nil + } + return nativeTrackingListener{Listener: ln} +} diff --git a/xray_native_test.go b/xray_native_test.go new file mode 100644 index 0000000..b1222f6 --- /dev/null +++ b/xray_native_test.go @@ -0,0 +1,1147 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" +) + +func TestSharedXHTTPListenerRoutesMostSpecificPath(t *testing.T) { + root := &nativeInbound{tag: "shared-proxy-xhttp", protocol: "vless", transport: "xhttp", path: "/", xhttpHost: "proxy.example", xhttpSessions: make(map[string]*nativeXHTTPSession)} + ssh := &nativeInbound{tag: "shared-ssh-xhttp", protocol: "ssh", transport: "xhttp", path: "/ssh", xhttpHost: "ssh.example", xhttpSessions: make(map[string]*nativeXHTTPSession)} + group, err := newNativeXHTTPListener("127.0.0.1:443", []*nativeInbound{root, ssh}) + if err != nil { + t.Fatalf("new shared XHTTP listener: %v", err) + } + + sshReq := httptest.NewRequest(http.MethodOptions, "http://ssh.example/ssh/session", nil) + sshRec := httptest.NewRecorder() + group.ServeHTTP(sshRec, sshReq) + if sshRec.Code != http.StatusOK { + t.Fatalf("/ssh routed to root instead of SSH inbound: status=%d", sshRec.Code) + } + + rootReq := httptest.NewRequest(http.MethodOptions, "http://proxy.example/session", nil) + rootRec := httptest.NewRecorder() + group.ServeHTTP(rootRec, rootReq) + if rootRec.Code != http.StatusOK { + t.Fatalf("/ routed incorrectly: status=%d", rootRec.Code) + } +} + +func TestSharedXHTTPListenerRejectsDuplicatePath(t *testing.T) { + a := &nativeInbound{tag: "a", transport: "xhttp", path: "/same"} + b := &nativeInbound{tag: "b", transport: "xhttp", path: "/same/"} + if _, err := newNativeXHTTPListener("127.0.0.1:443", []*nativeInbound{a, b}); err == nil { + t.Fatal("expected duplicate normalized XHTTP path to be rejected") + } +} + +func TestValidateNativeSharedXHTTPConfig(t *testing.T) { + valid := []byte(`{"inbounds":[ + {"tag":"legacy-proxy","listen":"0.0.0.0","port":443,"protocol":"vless","streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/legacy"}}}, + {"tag":"ssh","listen":"0.0.0.0","port":443,"protocol":"ssh","streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/ssh"}}} + ]}`) + if err := validateNativeInboundBindings(valid); err != nil { + t.Fatalf("valid shared endpoint rejected: %v", err) + } + + duplicate := []byte(`{"inbounds":[ + {"tag":"a","listen":"0.0.0.0","port":443,"protocol":"vless","streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/same"}}}, + {"tag":"b","listen":"0.0.0.0","port":443,"protocol":"ssh","streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/same/"}}} + ]}`) + if err := validateNativeInboundBindings(duplicate); err == nil { + t.Fatal("duplicate normalized XHTTP path was accepted") + } +} + +// startEchoServer starts a TCP server that echoes everything back and returns +// its port and a cleanup func. +func startEchoServer(t *testing.T) (int, func()) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("echo listen: %v", err) + } + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go io.Copy(c, c) + } + }() + return ln.Addr().(*net.TCPAddr).Port, func() { ln.Close() } +} + +// newTestInbound builds a native VLESS inbound with one known client, listening +// on an ephemeral port. Returns the inbound, the listen port, the client uuid, +// and a cleanup func. +func newTestInbound(t *testing.T, transport, path string) (*nativeInbound, int, [16]byte, func()) { + t.Helper() + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + t.Fatalf("rand: %v", err) + } + ib := &nativeInbound{ + tag: "test", + protocol: "vless", + transport: transport, + path: path, + clientsByID: map[[16]byte]*nativeXrayClient{id: {id: id, uuid: "test", email: "test@t"}}, + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("inbound listen: %v", err) + } + go ib.acceptLoop(ln) + port := ln.Addr().(*net.TCPAddr).Port + return ib, port, id, func() { ln.Close() } +} + +// vlessHeader builds a VLESS TCP request header targeting 127.0.0.1:targetPort. +func vlessHeader(id [16]byte, targetPort int) []byte { + var b bytes.Buffer + b.WriteByte(0) // version + b.Write(id[:]) // uuid + b.WriteByte(0) // addon length + b.WriteByte(vlessCmdTCP) // command + b.WriteByte(byte(targetPort >> 8)) + b.WriteByte(byte(targetPort)) + b.WriteByte(atypIPv4) // address type + b.Write([]byte{127, 0, 0, 1}) + return b.Bytes() +} + +func TestVLESSOverTCP(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(5 * time.Second)) + + // Send header + payload. + if _, err := conn.Write(vlessHeader(id, echoPort)); err != nil { + t.Fatalf("write header: %v", err) + } + if _, err := conn.Write([]byte("ping-tcp")); err != nil { + t.Fatalf("write payload: %v", err) + } + + // Read 2-byte VLESS response header. + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read response header: %v", err) + } + if resp[0] != 0 { + t.Fatalf("bad response version: %v", resp) + } + + // Read the echoed payload. + got := make([]byte, len("ping-tcp")) + if _, err := io.ReadFull(conn, got); err != nil { + t.Fatalf("read echo: %v", err) + } + if string(got) != "ping-tcp" { + t.Fatalf("echo mismatch: got %q", got) + } +} + +func vlessDNSSinkHeader(id [16]byte, cmd byte, host net.IP, port uint16) []byte { + var b bytes.Buffer + b.WriteByte(0) + b.Write(id[:]) + b.WriteByte(0) + b.WriteByte(cmd) + b.WriteByte(byte(port >> 8)) + b.WriteByte(byte(port)) + if ip4 := host.To4(); ip4 != nil { + b.WriteByte(atypIPv4) + b.Write(ip4) + } else { + b.WriteByte(atypIPv6) + b.Write(host.To16()) + } + return b.Bytes() +} + +func TestVLESSDNSSinkTargetFastIgnored(t *testing.T) { + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + + if _, err := conn.Write(vlessDNSSinkHeader(id, vlessCmdTCP, net.IPv4(0, 0, 0, 0), 0)); err != nil { + t.Fatalf("write sink header: %v", err) + } + + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read VLESS sink response: %v", err) + } + if resp[0] != 0 || resp[1] != 0 { + t.Fatalf("bad VLESS sink response: %v", resp) + } + + buf := make([]byte, 1) + if _, err := conn.Read(buf); err == nil { + t.Fatalf("sink target should close immediately after response") + } +} + +func TestNativeDNSSinkTargetDetection(t *testing.T) { + for _, host := range []string{"0.0.0.0", "::", "[::]", "::%lo"} { + if !isNativeDNSSinkTarget(host) { + t.Fatalf("%q should be detected as DNS sink", host) + } + } + for _, host := range []string{"", "127.0.0.1", "1.1.1.1", "example.com"} { + if isNativeDNSSinkTarget(host) { + t.Fatalf("%q should not be detected as DNS sink", host) + } + } +} + +func TestVLESSRejectsUnknownUUID(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + _, port, _, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(3 * time.Second)) + + var bad [16]byte // all-zero uuid, not registered + conn.Write(vlessHeader(bad, echoPort)) + conn.Write([]byte("should-not-echo")) + + // Server must reject: connection closed with no response bytes. + if n, err := conn.Read(make([]byte, 1)); err == nil && n > 0 { + t.Fatalf("expected rejection, but server responded with %d bytes", n) + } +} + +func TestVLESSOverWebSocket(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + _, port, id, stop := newTestInbound(t, "ws", "/vlws") + defer stop() + + raw, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer raw.Close() + raw.SetDeadline(time.Now().Add(5 * time.Second)) + + ws := wsClientHandshake(t, raw, "/vlws") + + // One frame carrying header + payload. + payload := append(vlessHeader(id, echoPort), []byte("ping-ws")...) + if _, err := ws.Write(payload); err != nil { + t.Fatalf("ws write: %v", err) + } + + // Read response header (2 bytes) + echo, possibly spanning frames. + buf := make([]byte, 0, 32) + want := 2 + len("ping-ws") + for len(buf) < want { + chunk := make([]byte, 64) + n, err := ws.Read(chunk) + if err != nil { + t.Fatalf("ws read: %v (got %q)", err, buf) + } + buf = append(buf, chunk[:n]...) + } + if buf[0] != 0 { + t.Fatalf("bad ws vless response: %v", buf[:2]) + } + if string(buf[2:want]) != "ping-ws" { + t.Fatalf("ws echo mismatch: got %q", buf[2:want]) + } +} + +func TestVLESSOverWebSocketEarlyData(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + _, port, id, stop := newTestInbound(t, "ws", "/vlws") + defer stop() + + raw, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer raw.Close() + raw.SetDeadline(time.Now().Add(5 * time.Second)) + + early := append(vlessHeader(id, echoPort), []byte("ping-ed")...) + proto := base64.RawURLEncoding.EncodeToString(early) + + var keyBytes [16]byte + rand.Read(keyBytes[:]) + key := base64.StdEncoding.EncodeToString(keyBytes[:]) + req := "GET /vlws HTTP/1.1\r\n" + + "Host: test\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Key: " + key + "\r\n" + + "Sec-WebSocket-Protocol: " + proto + "\r\n" + + "Sec-WebSocket-Version: 13\r\n\r\n" + if _, err := raw.Write([]byte(req)); err != nil { + t.Fatalf("handshake write: %v", err) + } + + br := bufio.NewReader(raw) + statusLine, err := br.ReadString('\n') + if err != nil { + t.Fatalf("read status: %v", err) + } + if !strings.Contains(statusLine, "101") { + t.Fatalf("ws handshake not 101: %q", statusLine) + } + sawProto := false + for { + line, err := br.ReadString('\n') + if err != nil { + t.Fatalf("read headers: %v", err) + } + if strings.Contains(line, proto) { + sawProto = true + } + if line == "\r\n" { + break + } + } + if !sawProto { + t.Fatalf("server did not echo Sec-WebSocket-Protocol") + } + + ws := &testWSConn{Conn: raw, r: br} + buf := make([]byte, 0, 32) + want := 2 + len("ping-ed") + for len(buf) < want { + chunk := make([]byte, 64) + n, err := ws.Read(chunk) + if err != nil { + t.Fatalf("ws read (early data dropped?): %v (got %q)", err, buf) + } + buf = append(buf, chunk[:n]...) + } + if buf[0] != 0 { + t.Fatalf("bad ws vless response: %v", buf[:2]) + } + if string(buf[2:want]) != "ping-ed" { + t.Fatalf("ws early-data echo mismatch: got %q", buf[2:want]) + } +} + +func TestVLESSOverXHTTPPacketUp(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + t.Fatalf("rand: %v", err) + } + ib := &nativeInbound{ + tag: "test-xhttp", + protocol: "vless", + transport: "xhttp", + path: normalizeXHTTPPath("/xhttp"), + xhttpMode: "packet-up", + xhttpMaxEachPostBytes: 1_000_000, + xhttpMaxBufferedPosts: 30, + xhttpSessions: make(map[string]*nativeXHTTPSession), + clientsByID: map[[16]byte]*nativeXrayClient{id: {id: id, uuid: "test", email: "test@t"}}, + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("xhttp listen: %v", err) + } + defer ln.Close() + go ib.serveXHTTPListener(ln) + port := ln.Addr().(*net.TCPAddr).Port + + client := &http.Client{Timeout: 5 * time.Second} + session := "session-test" + baseURL := "http://" + net.JoinHostPort("127.0.0.1", itoa(port)) + "/xhttp/" + session + + respCh := make(chan *http.Response, 1) + errCh := make(chan error, 1) + go func() { + resp, err := client.Get(baseURL) + if err != nil { + errCh <- err + return + } + respCh <- resp + }() + + var resp *http.Response + select { + case resp = <-respCh: + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("xhttp GET status: %s", resp.Status) + } + case err := <-errCh: + t.Fatalf("xhttp GET: %v", err) + case <-time.After(2 * time.Second): + t.Fatalf("xhttp GET did not open") + } + + payload := append(vlessHeader(id, echoPort), []byte("ping-xhttp")...) + postResp, err := client.Post(baseURL+"/0", "application/octet-stream", bytes.NewReader(payload)) + if err != nil { + t.Fatalf("xhttp POST: %v", err) + } + postResp.Body.Close() + if postResp.StatusCode != http.StatusOK { + t.Fatalf("xhttp POST status: %s", postResp.Status) + } + + got := make([]byte, 2+len("ping-xhttp")) + if _, err := io.ReadFull(resp.Body, got); err != nil { + t.Fatalf("xhttp read response: %v", err) + } + if got[0] != 0 { + t.Fatalf("bad xhttp vless response: %v", got[:2]) + } + if string(got[2:]) != "ping-xhttp" { + t.Fatalf("xhttp echo mismatch: got %q", got[2:]) + } +} + +func TestVLESSOverXHTTPPacketUpGET(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + t.Fatalf("rand: %v", err) + } + ib := &nativeInbound{ + tag: "test-xhttp-get-packet", + protocol: "vless", + transport: "xhttp", + path: normalizeXHTTPPath("/xhttp"), + xhttpMode: "packet-up", + xhttpMaxEachPostBytes: 1_000_000, + xhttpMaxBufferedPosts: 30, + xhttpSessions: make(map[string]*nativeXHTTPSession), + clientsByID: map[[16]byte]*nativeXrayClient{id: {id: id, uuid: "test", email: "test@t"}}, + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("xhttp listen: %v", err) + } + defer ln.Close() + go ib.serveXHTTPListener(ln) + port := ln.Addr().(*net.TCPAddr).Port + + client := &http.Client{Timeout: 5 * time.Second} + session := "session-get-packet" + baseURL := "http://" + net.JoinHostPort("127.0.0.1", itoa(port)) + "/xhttp/" + session + + respCh := make(chan *http.Response, 1) + errCh := make(chan error, 1) + go func() { + resp, err := client.Get(baseURL) + if err != nil { + errCh <- err + return + } + respCh <- resp + }() + + var resp *http.Response + select { + case resp = <-respCh: + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("xhttp GET status: %s", resp.Status) + } + case err := <-errCh: + t.Fatalf("xhttp GET: %v", err) + case <-time.After(2 * time.Second): + t.Fatalf("xhttp GET did not open") + } + + payload := append(vlessHeader(id, echoPort), []byte("ping-xhttp-get")...) + req, err := http.NewRequest(http.MethodGet, baseURL+"/0", bytes.NewReader(payload)) + if err != nil { + t.Fatalf("xhttp GET packet req: %v", err) + } + req.ContentLength = int64(len(payload)) + packetResp, err := client.Do(req) + if err != nil { + t.Fatalf("xhttp GET packet: %v", err) + } + packetResp.Body.Close() + if packetResp.StatusCode != http.StatusOK { + t.Fatalf("xhttp GET packet status: %s", packetResp.Status) + } + + got := make([]byte, 2+len("ping-xhttp-get")) + if _, err := io.ReadFull(resp.Body, got); err != nil { + t.Fatalf("xhttp read response: %v", err) + } + if got[0] != 0 { + t.Fatalf("bad xhttp vless response: %v", got[:2]) + } + if string(got[2:]) != "ping-xhttp-get" { + t.Fatalf("xhttp echo mismatch: got %q", got[2:]) + } +} + +func TestVLESSOverXHTTPOutOfOrderPacketUp(t *testing.T) { + echoPort, stopEcho := startEchoServer(t) + defer stopEcho() + + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + t.Fatalf("rand: %v", err) + } + ib := &nativeInbound{ + tag: "test-xhttp-reorder", + protocol: "vless", + transport: "xhttp", + path: normalizeXHTTPPath("/xhttp"), + xhttpMode: "packet-up", + xhttpMaxEachPostBytes: 1_000_000, + xhttpMaxBufferedPosts: 30, + xhttpSessions: make(map[string]*nativeXHTTPSession), + clientsByID: map[[16]byte]*nativeXrayClient{id: {id: id, uuid: "test", email: "test@t"}}, + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("xhttp listen: %v", err) + } + defer ln.Close() + go ib.serveXHTTPListener(ln) + port := ln.Addr().(*net.TCPAddr).Port + + client := &http.Client{Timeout: 4 * time.Second} + session := "session-reorder" + baseURL := "http://" + net.JoinHostPort("127.0.0.1", itoa(port)) + "/xhttp/" + session + + respCh := make(chan *http.Response, 1) + errCh := make(chan error, 1) + go func() { + resp, err := client.Get(baseURL) + if err != nil { + errCh <- err + return + } + respCh <- resp + }() + + var resp *http.Response + select { + case resp = <-respCh: + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("xhttp GET status: %s", resp.Status) + } + case err := <-errCh: + t.Fatalf("xhttp GET: %v", err) + case <-time.After(2 * time.Second): + t.Fatalf("xhttp GET did not open") + } + + full := append(vlessHeader(id, echoPort), []byte("reordered-payload-body")...) + third := len(full) / 3 + chunks := [][]byte{full[:third], full[third : 2*third], full[2*third:]} + + for _, seq := range []int{2, 1, 0} { + start := time.Now() + postResp, err := client.Post(baseURL+"/"+itoa(seq), "application/octet-stream", bytes.NewReader(chunks[seq])) + if err != nil { + t.Fatalf("xhttp POST seq=%d (head-of-line stall?): %v", seq, err) + } + postResp.Body.Close() + if postResp.StatusCode != http.StatusOK { + t.Fatalf("xhttp POST seq=%d status: %s", seq, postResp.Status) + } + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("xhttp POST seq=%d took %v; expected an immediate ack (not blocked on consumption)", seq, elapsed) + } + } + + got := make([]byte, 2+len("reordered-payload-body")) + if _, err := io.ReadFull(resp.Body, got); err != nil { + t.Fatalf("xhttp read response: %v", err) + } + if got[0] != 0 { + t.Fatalf("bad xhttp vless response: %v", got[:2]) + } + if string(got[2:]) != "reordered-payload-body" { + t.Fatalf("xhttp reassembled echo mismatch: got %q", got[2:]) + } +} + +func TestXHTTPRejectsBrowserGETWithoutSession(t *testing.T) { + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + t.Fatalf("rand: %v", err) + } + ib := &nativeInbound{ + tag: "test-xhttp-browser", + protocol: "vless", + transport: "xhttp", + path: normalizeXHTTPPath("/"), + xhttpMode: "packet-up", + xhttpMaxEachPostBytes: 1_000_000, + xhttpMaxBufferedPosts: 30, + xhttpSessions: make(map[string]*nativeXHTTPSession), + clientsByID: map[[16]byte]*nativeXrayClient{id: {id: id, uuid: "test", email: "test@t"}}, + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("xhttp listen: %v", err) + } + defer ln.Close() + go ib.serveXHTTPListener(ln) + port := ln.Addr().(*net.TCPAddr).Port + + client := &http.Client{Timeout: 5 * time.Second} + resp, err := client.Get("http://" + net.JoinHostPort("127.0.0.1", itoa(port)) + "/") + if err != nil { + t.Fatalf("browser GET: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("browser GET status = %d, want 400", resp.StatusCode) + } +} + +func TestParseUUID(t *testing.T) { + got, err := parseUUID("b831381d-6324-4d53-ad4f-8cda48b30811") + if err != nil { + t.Fatalf("parseUUID: %v", err) + } + want := [16]byte{0xb8, 0x31, 0x38, 0x1d, 0x63, 0x24, 0x4d, 0x53, 0xad, 0x4f, 0x8c, 0xda, 0x48, 0xb3, 0x08, 0x11} + if got != want { + t.Fatalf("uuid mismatch: %x != %x", got, want) + } + if _, err := parseUUID("not-a-uuid"); err == nil { + t.Fatalf("expected error for bad uuid") + } +} + +// --- minimal websocket client for the test --- + +type testWSConn struct { + net.Conn + r *bufio.Reader + readBuf []byte +} + +func wsClientHandshake(t *testing.T, conn net.Conn, path string) *testWSConn { + t.Helper() + var keyBytes [16]byte + rand.Read(keyBytes[:]) + key := base64.StdEncoding.EncodeToString(keyBytes[:]) + req := "GET " + path + " HTTP/1.1\r\n" + + "Host: test\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Key: " + key + "\r\n" + + "Sec-WebSocket-Version: 13\r\n\r\n" + if _, err := conn.Write([]byte(req)); err != nil { + t.Fatalf("ws client write handshake: %v", err) + } + br := bufio.NewReader(conn) + statusLine, err := br.ReadString('\n') + if err != nil { + t.Fatalf("ws client read status: %v", err) + } + if !strings.Contains(statusLine, "101") { + t.Fatalf("ws handshake not 101: %q", statusLine) + } + // Verify accept header and consume the rest of the header block. + sum := sha1.Sum([]byte(key + wsMagicGUID)) + wantAccept := base64.StdEncoding.EncodeToString(sum[:]) + sawAccept := false + for { + line, err := br.ReadString('\n') + if err != nil { + t.Fatalf("ws client read headers: %v", err) + } + if strings.Contains(line, wantAccept) { + sawAccept = true + } + if line == "\r\n" { + break + } + } + if !sawAccept { + t.Fatalf("ws server did not return correct Sec-WebSocket-Accept") + } + return &testWSConn{Conn: conn, r: br} +} + +func (c *testWSConn) Write(p []byte) (int, error) { + // Masked client binary frame. + var mask [4]byte + rand.Read(mask[:]) + n := len(p) + var hdr []byte + switch { + case n < 126: + hdr = []byte{0x82, 0x80 | byte(n)} + case n <= 0xffff: + hdr = []byte{0x82, 0x80 | 126, byte(n >> 8), byte(n)} + default: + hdr = make([]byte, 4) + hdr[0] = 0x82 + hdr[1] = 0x80 | 127 + // (8-byte length omitted; test payloads are small) + } + frame := append([]byte{}, hdr...) + frame = append(frame, mask[:]...) + masked := make([]byte, n) + for i := range p { + masked[i] = p[i] ^ mask[i&3] + } + frame = append(frame, masked...) + if _, err := c.Conn.Write(frame); err != nil { + return 0, err + } + return n, nil +} + +func (c *testWSConn) Read(p []byte) (int, error) { + for len(c.readBuf) == 0 { + var h [2]byte + if _, err := io.ReadFull(c.r, h[:]); err != nil { + return 0, err + } + length := int64(h[1] & 0x7f) + switch length { + case 126: + var ext [2]byte + io.ReadFull(c.r, ext[:]) + length = int64(binary.BigEndian.Uint16(ext[:])) + case 127: + var ext [8]byte + io.ReadFull(c.r, ext[:]) + length = int64(binary.BigEndian.Uint64(ext[:])) + } + payload := make([]byte, length) + if _, err := io.ReadFull(c.r, payload); err != nil { + return 0, err + } + c.readBuf = payload + } + n := copy(p, c.readBuf) + c.readBuf = c.readBuf[n:] + return n, nil +} + +func itoa(n int) string { return strconv.Itoa(n) } + +func TestVLESSUDPClassicDNSPacketFraming(t *testing.T) { + // A normal DNS query commonly has bytes 2/3 == 0x01/0x00. The old native + // auto-XUDP detector interpreted that as XUDP metadata and blocked waiting + // for another payload, so DNS over VLESS UDP never returned. + dnsQuery := []byte{ + 0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x04, 'f', 'a', 's', 't', + 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x01, 0x00, 0x01, + } + var framed bytes.Buffer + if err := writeVLESSLengthPacket(&framed, dnsQuery); err != nil { + t.Fatalf("write dns frame: %v", err) + } + got, err := readVLESSLengthPacket(&framed) + if err != nil { + t.Fatalf("read dns frame: %v", err) + } + if !bytes.Equal(got, dnsQuery) { + t.Fatalf("dns payload changed: got %x want %x", got, dnsQuery) + } +} + +func TestNormalizeNativeListenHostIPv6(t *testing.T) { + cases := map[string]string{ + "2804:10f8:ce00:520::7": "2804:10f8:ce00:520::7", + "[2804:10f8:ce00:520::7]": "2804:10f8:ce00:520::7", + "[[2804:10f8:ce00:520::7]]": "2804:10f8:ce00:520::7", + "[2804:10f8:ce00:520::7]:443": "2804:10f8:ce00:520::7", + "0.0.0.0:443": "0.0.0.0", + "127.0.0.1": "127.0.0.1", + "": "0.0.0.0", + } + for in, want := range cases { + if got := normalizeNativeListenHost(in); got != want { + t.Fatalf("normalizeNativeListenHost(%q) = %q, want %q", in, got, want) + } + } +} + +func TestNativeDialTargetKeepsIPv6Targets(t *testing.T) { + if got := normalizeNativeTargetHost("[2606:4700:4700::1111]"); got != "2606:4700:4700::1111" { + t.Fatalf("normalizeNativeTargetHost IPv6 bracket = %q", got) + } + if got := nativeDialNetwork("tcp", "2606:4700:4700::1111"); got != "tcp6" { + t.Fatalf("IPv6 TCP target must use tcp6, got %q", got) + } + if got := nativeDialNetwork("udp", "2606:4700:4700::1111"); got != "udp6" { + t.Fatalf("IPv6 UDP target must use udp6, got %q", got) + } + if got := nativeDialNetwork("tcp", "fast.com"); got != "tcp" { + t.Fatalf("domain targets must stay dual-stack tcp, got %q", got) + } + if got := nativeDialNetwork("udp", "one.one.one.one"); got != "udp" { + t.Fatalf("domain targets must stay dual-stack udp, got %q", got) + } +} + +func TestNativeLocalAddrForIPv6Tunnel(t *testing.T) { + local := nativeLocalAddrForDial("tcp", "2606:4700:4700::1111", "[2804:10f8:ce00:520::7]") + tcpAddr, ok := local.(*net.TCPAddr) + if !ok { + t.Fatalf("expected TCP local addr for IPv6 target, got %T", local) + } + if got := tcpAddr.IP.String(); got != "2804:10f8:ce00:520::7" { + t.Fatalf("wrong TCP local IPv6 source: %q", got) + } + + udpLocal := nativeLocalAddrForDial("udp", "2606:4700:4700::1111", "2804:10f8:ce00:520::7") + udpAddr, ok := udpLocal.(*net.UDPAddr) + if !ok { + t.Fatalf("expected UDP local addr for IPv6 target, got %T", udpLocal) + } + if got := udpAddr.IP.String(); got != "2804:10f8:ce00:520::7" { + t.Fatalf("wrong UDP local IPv6 source: %q", got) + } + + if local := nativeLocalAddrForDial("tcp", "2606:4700:4700::1111", "0.0.0.0"); local != nil { + t.Fatalf("must not bind IPv4 source to IPv6 target: %#v", local) + } +} + +func startUDPEchoServer(t *testing.T) (int, func()) { + t.Helper() + pc, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatalf("udp echo listen: %v", err) + } + go func() { + buf := make([]byte, 64*1024) + for { + n, addr, err := pc.ReadFrom(buf) + if err != nil { + return + } + _, _ = pc.WriteTo(buf[:n], addr) + } + }() + return pc.LocalAddr().(*net.UDPAddr).Port, func() { pc.Close() } +} + +func vlessMuxHeader(id [16]byte) []byte { + var b bytes.Buffer + b.WriteByte(0) + b.Write(id[:]) + b.WriteByte(0) + b.WriteByte(vlessCmdMux) + return b.Bytes() +} + +func buildMuxUDPFrame(sessionID uint16, host string, port int, payload []byte) []byte { + meta := []byte{byte(sessionID >> 8), byte(sessionID), nativeMuxStatusNew, nativeMuxOptionData, nativeMuxNetworkUDP} + meta = appendNativeMuxAddressPort(meta, host, uint16(port)) + var out bytes.Buffer + binary.Write(&out, binary.BigEndian, uint16(len(meta))) + out.Write(meta) + binary.Write(&out, binary.BigEndian, uint16(len(payload))) + out.Write(payload) + return out.Bytes() +} + +func buildMuxTCPFrame(sessionID uint16, host string, port int, payload []byte) []byte { + meta := []byte{byte(sessionID >> 8), byte(sessionID), nativeMuxStatusNew, nativeMuxOptionData, nativeMuxNetworkTCP} + meta = appendNativeMuxAddressPort(meta, host, uint16(port)) + var out bytes.Buffer + binary.Write(&out, binary.BigEndian, uint16(len(meta))) + out.Write(meta) + binary.Write(&out, binary.BigEndian, uint16(len(payload))) + out.Write(payload) + return out.Bytes() +} + +func buildMuxXUDPFrame(sessionID uint16, host string, port int, payload []byte, gid [8]byte) []byte { + meta := []byte{byte(sessionID >> 8), byte(sessionID), nativeMuxStatusNew, nativeMuxOptionData, nativeMuxNetworkUDP} + meta = appendNativeMuxAddressPort(meta, host, uint16(port)) + meta = append(meta, gid[:]...) + var out bytes.Buffer + binary.Write(&out, binary.BigEndian, uint16(len(meta))) + out.Write(meta) + // Official Mux.Cool/XUDP carries GlobalID in the outer New metadata. The + // following packet block is the UDP datagram itself, not another XUDP metadata + // stream. + binary.Write(&out, binary.BigEndian, uint16(len(payload))) + out.Write(payload) + return out.Bytes() +} + +func TestVLESSMuxUDPDoesNotStall(t *testing.T) { + udpPort, stopUDP := startUDPEchoServer(t) + defer stopUDP() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := conn.Write(vlessMuxHeader(id)); err != nil { + t.Fatalf("write mux header: %v", err) + } + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read mux response header: %v", err) + } + if resp[0] != 0 || resp[1] != 0 { + t.Fatalf("bad mux vless response: %v", resp) + } + + want := []byte("quic-over-mux") + if _, err := conn.Write(buildMuxUDPFrame(7, "127.0.0.1", udpPort, want)); err != nil { + t.Fatalf("write mux udp frame: %v", err) + } + meta, err := readNativeMuxMetadata(conn) + if err != nil { + t.Fatalf("read mux response meta: %v", err) + } + if meta.sessionID != 7 || meta.status != nativeMuxStatusKeep || meta.option&nativeMuxOptionData == 0 { + t.Fatalf("bad mux response metadata: %#v", meta) + } + got, err := readNativeMuxDataBlock(conn) + if err != nil { + t.Fatalf("read mux response payload: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("mux udp echo mismatch: got %q want %q", got, want) + } +} + +func TestVLESSMuxXUDPDoesNotStall(t *testing.T) { + udpPort, stopUDP := startUDPEchoServer(t) + defer stopUDP() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := conn.Write(vlessMuxHeader(id)); err != nil { + t.Fatalf("write mux header: %v", err) + } + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read mux response header: %v", err) + } + + want := []byte("quic-over-xudp") + gid := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} + if _, err := conn.Write(buildMuxXUDPFrame(9, "127.0.0.1", udpPort, want, gid)); err != nil { + t.Fatalf("write mux xudp frame: %v", err) + } + meta, err := readNativeMuxMetadata(conn) + if err != nil { + t.Fatalf("read mux xudp response meta: %v", err) + } + if meta.sessionID != 9 || meta.status != nativeMuxStatusKeep || meta.option&nativeMuxOptionData == 0 { + t.Fatalf("bad mux xudp response metadata: %#v", meta) + } + if meta.host != "127.0.0.1" || int(meta.port) != udpPort { + t.Fatalf("xudp response did not preserve UDP endpoint: %#v", meta) + } + got, err := readNativeMuxDataBlock(conn) + if err != nil { + t.Fatalf("read xudp response payload: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("mux xudp echo mismatch: got %q want %q", got, want) + } +} + +func TestVLESSMuxXUDPPayloadLookingLikeMetadataDoesNotStall(t *testing.T) { + udpPort, stopUDP := startUDPEchoServer(t) + defer stopUDP() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := conn.Write(vlessMuxHeader(id)); err != nil { + t.Fatalf("write mux header: %v", err) + } + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read mux response header: %v", err) + } + + // This payload intentionally looks like old inner-XUDP metadata. Mux.Cool + // packet mode must still forward it as one UDP datagram and must not block + // waiting for another fake payload block. + want := []byte{0, 0, 2, 1, 'q', 'u', 'i', 'c'} + gid := [8]byte{8, 7, 6, 5, 4, 3, 2, 1} + if _, err := conn.Write(buildMuxXUDPFrame(10, "127.0.0.1", udpPort, want, gid)); err != nil { + t.Fatalf("write mux xudp frame: %v", err) + } + meta, err := readNativeMuxMetadata(conn) + if err != nil { + t.Fatalf("read mux xudp response meta: %v", err) + } + if meta.sessionID != 10 || meta.status != nativeMuxStatusKeep || meta.option&nativeMuxOptionData == 0 { + t.Fatalf("bad mux xudp response metadata: %#v", meta) + } + got, err := readNativeMuxDataBlock(conn) + if err != nil { + t.Fatalf("read xudp response payload: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("mux xudp metadata-looking payload changed: got %q want %q", got, want) + } +} + +func TestVLESSMuxTCPDoesNotStall(t *testing.T) { + tcpPort, stopTCP := startEchoServer(t) + defer stopTCP() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := conn.Write(vlessMuxHeader(id)); err != nil { + t.Fatalf("write mux header: %v", err) + } + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read mux response header: %v", err) + } + + want := []byte("tcp-over-mux") + if _, err := conn.Write(buildMuxTCPFrame(11, "127.0.0.1", tcpPort, want)); err != nil { + t.Fatalf("write mux tcp frame: %v", err) + } + meta, err := readNativeMuxMetadata(conn) + if err != nil { + t.Fatalf("read mux tcp response meta: %v", err) + } + if meta.sessionID != 11 || meta.status != nativeMuxStatusKeep || meta.option&nativeMuxOptionData == 0 { + t.Fatalf("bad mux tcp response metadata: %#v", meta) + } + got, err := readNativeMuxDataBlock(conn) + if err != nil { + t.Fatalf("read mux tcp response payload: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("mux tcp echo mismatch: got %q want %q", got, want) + } +} + +func TestVLESSMuxSlowDialDoesNotBlockOtherSessions(t *testing.T) { + tcpPort, stopTCP := startEchoServer(t) + defer stopTCP() + _, port, id, stop := newTestInbound(t, "tcp", "") + defer stop() + + conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", itoa(port))) + if err != nil { + t.Fatalf("dial inbound: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(4 * time.Second)) + + if _, err := conn.Write(vlessMuxHeader(id)); err != nil { + t.Fatalf("write mux header: %v", err) + } + resp := make([]byte, 2) + if _, err := io.ReadFull(conn, resp); err != nil { + t.Fatalf("read mux response header: %v", err) + } + + if _, err := conn.Write(buildMuxTCPFrame(1, "192.0.2.1", 80, []byte("slow"))); err != nil { + t.Fatalf("write slow mux frame: %v", err) + } + want := []byte("fast-session") + if _, err := conn.Write(buildMuxTCPFrame(2, "127.0.0.1", tcpPort, want)); err != nil { + t.Fatalf("write fast mux frame: %v", err) + } + + for { + meta, err := readNativeMuxMetadata(conn) + if err != nil { + t.Fatalf("read fast session response meta (head-of-line stall?): %v", err) + } + var got []byte + if meta.option&nativeMuxOptionData != 0 { + got, err = readNativeMuxDataBlock(conn) + if err != nil { + t.Fatalf("read mux response payload: %v", err) + } + } + // Some networks reject TEST-NET immediately instead of letting the dial + // time out. Ignore that session-1 error frame and keep waiting for the + // independent fast session. + if meta.sessionID != 2 { + continue + } + if meta.status != nativeMuxStatusKeep || meta.option&nativeMuxOptionData == 0 { + t.Fatalf("expected session 2 keep-data frame, got: %#v", meta) + } + if !bytes.Equal(got, want) { + t.Fatalf("fast session echo mismatch: got %q want %q", got, want) + } + break + } +} diff --git a/xray_native_tuning.go b/xray_native_tuning.go new file mode 100644 index 0000000..1e71fd2 --- /dev/null +++ b/xray_native_tuning.go @@ -0,0 +1,139 @@ +package main + +import ( + "runtime" + "sync/atomic" + "time" +) + +type XrayNativeTuning struct { + RuntimeGOMAXPROCS int `json:"runtime_gomaxprocs,omitempty"` + MuxGlobalSessions int `json:"mux_global_sessions,omitempty"` + MaxConcurrentConnections int `json:"max_concurrent_connections,omitempty"` + MaxConcurrentXHTTPRequests int `json:"max_concurrent_xhttp_requests,omitempty"` + XHTTPMaxSessions int `json:"xhttp_max_sessions,omitempty"` + TracePackets bool `json:"trace_packets,omitempty"` +} + +const ( + defaultNativeRuntimeGOMAXPROCS = 0 + defaultNativeMuxGlobalSessions = 32768 + // Transport sockets, XHTTP requests, and XHTTP sessions are VPN traffic, not + // website requests. Keep the legacy JSON fields for config compatibility, but + // always normalize them to unlimited. Actual resource protection is provided by + // socket/HTTP flow control and the bounded byte queues in xray_xhttp.go. + defaultNativeMaxConnections = -1 + defaultNativeMaxXHTTPRequests = -1 + + fixedNativeMuxMaxSessions = 64 + fixedNativeMuxUDPIdleMS = 120000 + fixedNativeMuxUDPReadBuffer = 256 * 1024 + fixedNativeMuxUDPWriteBuffer = 256 * 1024 + + defaultNativeXHTTPMaxSessions = -1 + // Packet-up posts are also protected by byte budgets in xray_xhttp.go. Keep + // the default reorder queue modest so thousands of unauthenticated sessions + // cannot consume large amounts of memory merely by allocating empty channel + // buffers. Operators may request more, up to the hard cap enforced there. + defaultNativeXHTTPBufferedPosts = 64 + + // These are simultaneous resource-safety windows, not request-rate limits. + // They are deliberately far above the expected 6-8K connected-user load, but + // finite so a reconnect storm, broken CDN, or hostile client cannot retain an + // unbounded number of sockets, HTTP handlers, sessions, and goroutine stacks. + // Transport Accept waits at capacity (kernel backpressure); XHTTP overloads + // receive 503 rather than the web-rate-limit semantics of 429. + fixedNativeMaxTransportConnections = 65536 + fixedNativeMaxXHTTPRequests = 65536 + fixedNativeMaxXHTTPSessions = 65536 + fixedNativeHTTP2ConcurrentStreams = 4096 + fixedNativeXHTTPWriteTimeoutMS = 60 * 1000 + + // Backstop reaper for connected XHTTP VPN sessions. The stream-down GET's + // request context is the primary lifetime owner, but behind a CDN that context + // frequently never fires when a client silently drops (mobile networks, CDN + // connection pooling, half-open TCP). When it doesn't, an idle SSH backend + // never errors either, so the session, its goroutines, socket/fd, and SSH + // connection leak until the whole process restarts. That accumulation is what + // drove the recurring XHTTP 502s that only a reboot cleared: the origin slowly + // ran out of fds/memory and could no longer serve new stream-down GETs. + // + // This sweeper only ever reaps sessions with genuinely stale lastSeen. lastSeen + // is refreshed on every successful read OR write via nativeXHTTPConn.onActivity, + // so any tunnel still passing data or keepalives is never touched -- only a + // session with zero bytes in BOTH directions for the full window (i.e. one that + // looks dead) is closed. 20 minutes is generous enough not to disturb a + // genuinely idle-but-alive tunnel while still bounding resource growth under + // heavy 6-8K-user churn. Zero disables the connected-session sweeper. + fixedNativeXHTTPIdleMS = 20 * 60 * 1000 +) + +var ( + nativeTuneRuntimeGOMAXPROCS atomic.Int64 + nativeTuneMuxGlobalSessions atomic.Int64 + nativeTuneTracePackets atomic.Bool +) + +func init() { + applyNativeXrayTuning(nil) +} + +func normalizeNativeXrayTuning(t *XrayNativeTuning) XrayNativeTuning { + if t == nil { + t = &XrayNativeTuning{} + } + out := *t + if out.RuntimeGOMAXPROCS < 0 { + out.RuntimeGOMAXPROCS = defaultNativeRuntimeGOMAXPROCS + } + if out.MuxGlobalSessions <= 0 { + out.MuxGlobalSessions = defaultNativeMuxGlobalSessions + } + // Ignore every old positive/zero admission ceiling. This migration is + // deliberately unconditional so upgrading an existing server immediately + // removes the old 4K/8K/32K web-style caps without requiring a panel save. + out.MaxConcurrentConnections = defaultNativeMaxConnections + out.MaxConcurrentXHTTPRequests = defaultNativeMaxXHTTPRequests + out.XHTTPMaxSessions = defaultNativeXHTTPMaxSessions + return out +} + +func applyNativeXrayTuning(t *XrayNativeTuning) XrayNativeTuning { + out := normalizeNativeXrayTuning(t) + gomax := out.RuntimeGOMAXPROCS + if gomax <= 0 { + gomax = runtime.NumCPU() + } + if gomax < 1 { + gomax = 1 + } + runtime.GOMAXPROCS(gomax) + nativeTuneRuntimeGOMAXPROCS.Store(int64(gomax)) + nativeTuneMuxGlobalSessions.Store(int64(out.MuxGlobalSessions)) + nativeTuneTracePackets.Store(out.TracePackets) + return out +} + +func nativeRuntimeGOMAXPROCS() int { return int(nativeTuneRuntimeGOMAXPROCS.Load()) } +func nativeMuxGlobalSessionLimit() int { return int(nativeTuneMuxGlobalSessions.Load()) } +func nativeTracePacketsEnabled() bool { return nativeTuneTracePackets.Load() } + +func nativeMuxMaxSessionLimit() int { return fixedNativeMuxMaxSessions } +func nativeMuxUDPReadBufferSize() int { return fixedNativeMuxUDPReadBuffer } +func nativeMuxUDPWriteBufferSize() int { return fixedNativeMuxUDPWriteBuffer } +func nativeXHTTPBufferedPostLimit() int { return defaultNativeXHTTPBufferedPosts } +func nativeHTTP2MaxConcurrentStreams() uint32 { + return fixedNativeHTTP2ConcurrentStreams +} +func nativeTransportConnectionLimit() int { return fixedNativeMaxTransportConnections } +func nativeXHTTPRequestLimit() int { return fixedNativeMaxXHTTPRequests } +func nativeXHTTPSessionLimit() int { return fixedNativeMaxXHTTPSessions } +func nativeXHTTPWriteTimeout() time.Duration { + return fixedNativeXHTTPWriteTimeoutMS * time.Millisecond +} +func nativeMuxUDPIdleTimeout() time.Duration { + return fixedNativeMuxUDPIdleMS * time.Millisecond +} +func nativeXHTTPIdleTimeout() time.Duration { + return fixedNativeXHTTPIdleMS * time.Millisecond +} diff --git a/xray_native_udp.go b/xray_native_udp.go new file mode 100644 index 0000000..9f5331e --- /dev/null +++ b/xray_native_udp.go @@ -0,0 +1,421 @@ +package main + +import ( + "context" + "encoding/binary" + "fmt" + "io" + "net" + "sync" + "time" + + "golang.org/x/time/rate" +) + +const ( + nativeUDPMaxPacket = 65535 + nativeUDPBufferSize = 64 * 1024 + nativeUDPIdle = 2 * time.Minute +) + +// nativeVLESSUDPTunnel implements VLESS UDP-over-stream framing for a normal +// VLESS CommandUDP request. Xray uses classic 2-byte length-prefixed packets +// for this command. Do not auto-detect XUDP here: real DNS queries often have +// bytes 2/3 equal to 0x01/0x00, which looked like our old loose XUDP metadata +// check and caused the server to block waiting for a fake second payload. +// XUDP belongs to VLESS CommandMux and is handled separately when Mux support +// is implemented. +func nativeVLESSUDPTunnel(client io.ReadWriteCloser, backend net.Conn, uuid, email string, quotaState *xrayNativeQuotaState, up, down *rate.Limiter) { + defer xrayRecover(fmt.Sprintf("native xray VLESS UDP tunnel user=%s", email)) + + upMeter := newTrafficMeter(uuid, email, true, quotaState) + downMeter := newTrafficMeter(uuid, email, false, quotaState) + + var wg sync.WaitGroup + var closeOnce sync.Once + ctx, cancel := context.WithCancel(context.Background()) + closeAll := func() { + closeOnce.Do(func() { + cancel() + _ = backend.Close() + _ = client.Close() + }) + } + + wg.Add(1) + xrayGo("native xray VLESS UDP uplink", func() { + defer wg.Done() + defer closeAll() + for { + payload, err := readVLESSLengthPacket(client) + if err != nil { + if err != io.EOF { + xrayLogf("native xray: VLESS UDP client read failed: %v", err) + } + return + } + if len(payload) == 0 { + continue + } + if err := waitNativeRate(ctx, up, len(payload)); err != nil { + return + } + quotaReservation, err := reserveNativePacketQuota(upMeter, len(payload)) + if err != nil { + return + } + if err := quotaReservation.wait(ctx); err != nil { + return + } + n, err := backend.Write(payload) + quotaReservation.finish(n) + if err != nil { + xrayLogf("native xray: VLESS UDP backend write failed: %v", err) + return + } + } + }) + + wg.Add(1) + xrayGo("native xray VLESS UDP downlink", func() { + defer wg.Done() + defer closeAll() + buf := make([]byte, nativeUDPBufferSize) + for { + _ = backend.SetReadDeadline(time.Now().Add(nativeUDPIdle)) + n, err := backend.Read(buf) + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Timeout() { + return + } + if err != io.EOF { + xrayLogf("native xray: VLESS UDP backend read failed: %v", err) + } + return + } + if n <= 0 { + continue + } + if err := waitNativeRate(ctx, down, n); err != nil { + return + } + quotaReservation, err := reserveNativePacketQuota(downMeter, n) + if err != nil { + return + } + if err := quotaReservation.wait(ctx); err != nil { + return + } + if err := writeVLESSLengthPacket(client, buf[:n]); err != nil { + quotaReservation.finish(0) + xrayLogf("native xray: VLESS UDP client write failed: %v", err) + return + } + quotaReservation.finish(n) + } + }) + + wg.Wait() + upMeter.flush() + downMeter.flush() + closeAll() +} + +type vlessUDPPacketCodec struct { + mu sync.RWMutex + decided bool + xudp bool +} + +func (c *vlessUDPPacketCodec) setXUDP(v bool) { + c.mu.Lock() + if !c.decided { + c.decided = true + c.xudp = v + } + c.mu.Unlock() +} + +func (c *vlessUDPPacketCodec) useXUDP() bool { + c.mu.RLock() + defer c.mu.RUnlock() + return c.decided && c.xudp +} + +func (c *vlessUDPPacketCodec) Read(r io.Reader) ([]byte, error) { + if c.useXUDP() { + return readVLESSXUDPPacket(r) + } + return c.readAuto(r) +} + +func (c *vlessUDPPacketCodec) Write(w io.Writer, payload []byte) error { + if c.useXUDP() { + return writeVLESSXUDPPacket(w, payload) + } + return writeVLESSLengthPacket(w, payload) +} + +func (c *vlessUDPPacketCodec) readAuto(r io.Reader) ([]byte, error) { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n == 0 { + c.setXUDP(false) + return []byte{}, nil + } + if n > nativeUDPMaxPacket { + return nil, fmt.Errorf("udp packet too large: %d", n) + } + + // XUDP starts with a metadata frame length, not a payload length. Metadata is + // small and has command/option bytes at offsets 2/3 after the two-byte mux ID. + // Read a possible metadata frame once and fall back to normal length-prefixed + // UDP if it does not match the XUDP shape. This lets the native emulator work + // with clients whose default packet encoding is xudp while preserving classic + // VLESS UDP framing. + if n >= 4 && n <= 512 { + candidate := make([]byte, n) + if _, err := io.ReadFull(r, candidate); err != nil { + return nil, err + } + if isVLESSXUDPMetadata(candidate) { + c.setXUDP(true) + return readVLESSXUDPPayloadAfterMeta(r, candidate) + } + c.setXUDP(false) + return candidate, nil + } + + c.setXUDP(false) + pkt := make([]byte, n) + _, err := io.ReadFull(r, pkt) + return pkt, err +} + +func readVLESSLengthPacket(r io.Reader) ([]byte, error) { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n == 0 { + return []byte{}, nil + } + if n > nativeUDPMaxPacket { + return nil, fmt.Errorf("udp packet too large: %d", n) + } + pkt := make([]byte, n) + _, err := io.ReadFull(r, pkt) + return pkt, err +} + +func writeVLESSLengthPacket(w io.Writer, payload []byte) error { + if len(payload) > nativeUDPMaxPacket { + return fmt.Errorf("udp packet too large: %d", len(payload)) + } + // One Write is important for XHTTP because the response writer flushes once per + // Write. Two writes per UDP packet doubles flush/syscall pressure. + frame := make([]byte, 0, 2+len(payload)) + frame = appendUint16(frame, uint16(len(payload))) + frame = append(frame, payload...) + _, err := w.Write(frame) + return err +} + +func isVLESSXUDPMetadata(meta []byte) bool { + if len(meta) < 4 { + return false + } + cmd := meta[2] + opt := meta[3] + if cmd != 1 && cmd != 2 && cmd != 4 { // New, Keep, End/discard + return false + } + return opt == 0 || opt == 1 +} + +func readVLESSXUDPPacket(r io.Reader) ([]byte, error) { + for { + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n < 4 || n > 512 { + return nil, fmt.Errorf("bad xudp metadata length: %d", n) + } + meta := make([]byte, n) + if _, err := io.ReadFull(r, meta); err != nil { + return nil, err + } + if !isVLESSXUDPMetadata(meta) { + return nil, fmt.Errorf("bad xudp metadata command/option") + } + payload, err := readVLESSXUDPPayloadAfterMeta(r, meta) + if err != nil { + return nil, err + } + if payload != nil { + return payload, nil + } + } +} + +func readVLESSXUDPPayloadAfterMeta(r io.Reader, meta []byte) ([]byte, error) { + if len(meta) < 4 { + return nil, io.ErrUnexpectedEOF + } + if meta[2] == 4 { // discard/end marker + return nil, nil + } + if meta[3] != 1 { // no payload attached + return nil, nil + } + var lenBuf [2]byte + if _, err := io.ReadFull(r, lenBuf[:]); err != nil { + return nil, err + } + n := int(binary.BigEndian.Uint16(lenBuf[:])) + if n == 0 { + return []byte{}, nil + } + if n > nativeUDPMaxPacket { + return nil, fmt.Errorf("xudp payload too large: %d", n) + } + pkt := make([]byte, n) + _, err := io.ReadFull(r, pkt) + return pkt, err +} + +func writeVLESSXUDPPacket(w io.Writer, payload []byte) error { + if len(payload) > nativeUDPMaxPacket { + return fmt.Errorf("udp packet too large: %d", len(payload)) + } + // Metadata length 4, mux session id 0, command Keep, option payload-present. + // This is accepted by Xray's xudp.PacketReader for responses when the UDP + // destination is already known from the request header. + var header [8]byte + binary.BigEndian.PutUint16(header[0:2], 4) + header[2] = 0 + header[3] = 0 + header[4] = 2 // Keep + header[5] = 1 // Opt: payload follows + binary.BigEndian.PutUint16(header[6:8], uint16(len(payload))) + if _, err := w.Write(header[:]); err != nil { + return err + } + _, err := w.Write(payload) + return err +} + +// nativeVMessUDPTunnel maps one VMess body chunk to one UDP datagram. VMess AEAD +// chunking already preserves packet boundaries, so no extra VLESS length prefix +// is added inside the encrypted body. +func nativeVMessUDPTunnel(client nativeVMessStream, backend net.Conn, uuid, email string, quotaState *xrayNativeQuotaState, up, down *rate.Limiter) { + defer xrayRecover(fmt.Sprintf("native xray VMess UDP tunnel user=%s", email)) + + upMeter := newTrafficMeter(uuid, email, true, quotaState) + downMeter := newTrafficMeter(uuid, email, false, quotaState) + + var wg sync.WaitGroup + var closeOnce sync.Once + ctx, cancel := context.WithCancel(context.Background()) + closeAll := func() { + closeOnce.Do(func() { + cancel() + _ = backend.Close() + _ = client.Close() + }) + } + + wg.Add(1) + xrayGo("native xray VMess UDP uplink", func() { + defer wg.Done() + defer closeAll() + for { + pkt, err := client.ReadPacket() + if err != nil { + if err != io.EOF { + xrayLogf("native xray: VMess UDP client read failed: %v", err) + } + return + } + if len(pkt) == 0 { + continue + } + if err := waitNativeRate(ctx, up, len(pkt)); err != nil { + return + } + quotaReservation, err := reserveNativePacketQuota(upMeter, len(pkt)) + if err != nil { + return + } + if err := quotaReservation.wait(ctx); err != nil { + return + } + n, err := backend.Write(pkt) + quotaReservation.finish(n) + if err != nil { + xrayLogf("native xray: VMess UDP backend write failed: %v", err) + return + } + } + }) + + wg.Add(1) + xrayGo("native xray VMess UDP downlink", func() { + defer wg.Done() + defer closeAll() + buf := make([]byte, nativeUDPBufferSize) + for { + _ = backend.SetReadDeadline(time.Now().Add(nativeUDPIdle)) + n, err := backend.Read(buf) + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Timeout() { + return + } + if err != io.EOF { + xrayLogf("native xray: VMess UDP backend read failed: %v", err) + } + return + } + if n <= 0 { + continue + } + if err := waitNativeRate(ctx, down, n); err != nil { + return + } + quotaReservation, err := reserveNativePacketQuota(downMeter, n) + if err != nil { + return + } + if err := quotaReservation.wait(ctx); err != nil { + return + } + if err := client.WritePacket(buf[:n]); err != nil { + quotaReservation.finish(0) + xrayLogf("native xray: VMess UDP client write failed: %v", err) + return + } + quotaReservation.finish(n) + } + }) + + wg.Wait() + upMeter.flush() + downMeter.flush() + closeAll() +} + +func waitNativeRate(ctx context.Context, lim *rate.Limiter, n int) error { + if lim == nil || n <= 0 { + return nil + } + if ctx == nil { + ctx = context.Background() + } + return lim.WaitN(ctx, n) +} diff --git a/xray_quota.go b/xray_quota.go new file mode 100644 index 0000000..930f884 --- /dev/null +++ b/xray_quota.go @@ -0,0 +1,513 @@ +package main + +import ( + "context" + "io" + "strings" + "sync" + "time" + + "golang.org/x/time/rate" +) + +type xrayNativeQuotaState struct { + // trafficMu establishes a clean reset boundary. Native stream and packet + // writers hold a read lock from quota reservation through the actual write + // and metering; traffic resets take the write lock. This prevents an + // in-flight pre-reset reservation from being accounted in the new period or + // subtracting from freshly reset usage. + trafficMu sync.RWMutex + mu sync.Mutex + usedBytes int64 + quotaBytes int64 + action string + throttleMbps int + limiter *rate.Limiter + generation uint64 + maxConns int + activeConns int + owner string + expiresAt time.Time + hasExpiry bool + connections map[io.Closer]struct{} +} + +func (m *XrayManager) reloadNativeQuotaPolicies() { + if statsStore == nil { + return + } + metas, err := statsStore.ListAllXrayClients(context.Background()) + if err != nil { + xrayLogf("xray native quota: load policies failed: %v", err) + return + } + next := make(map[string]*xrayNativeQuotaState, len(metas)) + for _, meta := range metas { + if meta == nil || strings.TrimSpace(meta.UUID) == "" { + continue + } + next[meta.UUID] = newXrayNativeQuotaState(meta) + } + m.nativeQuotaMu.Lock() + m.nativeQuotaByUUID = next + m.nativeQuotaMu.Unlock() +} + +func newXrayNativeQuotaState(meta *XrayClientMeta) *xrayNativeQuotaState { + used := meta.TotalUplinkBytes + meta.TotalDownlinkBytes + if used < 0 { + used = 0 + } + return &xrayNativeQuotaState{ + usedBytes: used, + quotaBytes: meta.DataQuotaBytes, + action: normalizeQuotaAction(meta.QuotaAction), + throttleMbps: quotaThrottleMbpsOrDefault(meta.QuotaThrottleMbps), + generation: 1, + maxConns: normalizeXrayMaxConns(meta.MaxConns), + owner: strings.TrimSpace(meta.OwnerUsername), + hasExpiry: meta.ExpiresAt != nil, + expiresAt: xrayExpiryValue(meta.ExpiresAt), + } +} + +func xrayExpiryValue(expiry *time.Time) time.Time { + if expiry == nil { + return time.Time{} + } + return *expiry +} + +func normalizeXrayMaxConns(v int) int { + if v < 0 { + return 0 + } + return v +} + +func (m *XrayManager) setNativeQuotaPolicy(meta *XrayClientMeta) { + if meta == nil || strings.TrimSpace(meta.UUID) == "" { + return + } + uuid := strings.TrimSpace(meta.UUID) + m.nativeQuotaMu.Lock() + if m.nativeQuotaByUUID == nil { + m.nativeQuotaByUUID = make(map[string]*xrayNativeQuotaState) + } + existing := m.nativeQuotaByUUID[uuid] + if existing == nil { + m.nativeQuotaByUUID[uuid] = newXrayNativeQuotaState(meta) + m.nativeQuotaMu.Unlock() + return + } + m.nativeQuotaMu.Unlock() + + existing.mu.Lock() + existing.quotaBytes = meta.DataQuotaBytes + existing.action = normalizeQuotaAction(meta.QuotaAction) + existing.throttleMbps = quotaThrottleMbpsOrDefault(meta.QuotaThrottleMbps) + existing.maxConns = normalizeXrayMaxConns(meta.MaxConns) + existing.owner = strings.TrimSpace(meta.OwnerUsername) + existing.hasExpiry = meta.ExpiresAt != nil + existing.expiresAt = xrayExpiryValue(meta.ExpiresAt) + existing.limiter = nil + existing.mu.Unlock() +} + +func (m *XrayManager) removeNativeQuotaPolicy(uuid string) { + uuid = strings.TrimSpace(uuid) + if uuid == "" { + return + } + m.nativeQuotaMu.Lock() + state := m.nativeQuotaByUUID[uuid] + delete(m.nativeQuotaByUUID, uuid) + m.nativeQuotaMu.Unlock() + closeNativeClientConnections(state) + + // Do not retain failed traffic/active deltas for a client that no longer + // exists. This also bounds the pending maps during a prolonged DB outage. + m.nativeDBMu.Lock() + delete(m.nativeTrafficPending, uuid) + delete(m.nativeActivePending, uuid) + m.nativeDBMu.Unlock() +} + +func (m *XrayManager) resetNativeQuotaUsage(uuid string) { + uuid = strings.TrimSpace(uuid) + m.nativeQuotaMu.RLock() + state := m.nativeQuotaByUUID[uuid] + m.nativeQuotaMu.RUnlock() + if state == nil { + return + } + state.trafficMu.Lock() + defer state.trafficMu.Unlock() + state.mu.Lock() + state.usedBytes = 0 + state.limiter = nil + state.generation++ + if state.generation == 0 { + state.generation = 1 + } + state.mu.Unlock() +} + +func (m *XrayManager) resetNativeTrafficAccounting(ctx context.Context, store *Store, uuid, email string) error { + state := m.nativeQuotaState(uuid) + if state != nil { + state.trafficMu.Lock() + defer state.trafficMu.Unlock() + state.mu.Lock() + defer state.mu.Unlock() + } + + m.nativeTrafficPersistMu.Lock() + defer m.nativeTrafficPersistMu.Unlock() + + // Remove this client's queued pre-reset delta while holding only the short + // map mutex. The database call may take seconds during an outage; keeping + // nativeDBMu locked across it would stall traffic/accounting updates for + // every other native user and could amplify a slow database into a goroutine + // pile-up. + m.nativeDBMu.Lock() + key := strings.TrimSpace(uuid) + var pending xrayPendingTraffic + hadPending := false + if m.nativeTrafficPending != nil { + pending, hadPending = m.nativeTrafficPending[key] + delete(m.nativeTrafficPending, key) + } + m.nativeDBMu.Unlock() + + err := store.ResetXrayClientTraffic(ctx, uuid) + if err != nil && hadPending && pending.State == state { + m.nativeDBMu.Lock() + if m.nativeTrafficPending == nil { + m.nativeTrafficPending = make(map[string]xrayPendingTraffic) + } + current := m.nativeTrafficPending[key] + if current.State != nil && current.State != state { + current = xrayPendingTraffic{} + } + if current.Email == "" { + current.Email = pending.Email + } + current.Uplink += pending.Uplink + current.Downlink += pending.Downlink + current.State = state + m.nativeTrafficPending[key] = current + m.nativeDBMu.Unlock() + } + if err != nil { + return err + } + if state != nil { + state.usedBytes = 0 + state.limiter = nil + state.generation++ + if state.generation == 0 { + state.generation = 1 + } + } + + m.statsMu.Lock() + for _, key := range []string{strings.TrimSpace(email), strings.TrimSpace(uuid)} { + if key == "" { + continue + } + if runtime, ok := m.statsByEmail[key]; ok { + runtime.Uplink = 0 + runtime.Downlink = 0 + m.statsByEmail[key] = runtime + } + } + m.statsMu.Unlock() + return nil +} + +func (m *XrayManager) nativeQuotaState(uuid string) *xrayNativeQuotaState { + m.nativeQuotaMu.RLock() + state := m.nativeQuotaByUUID[strings.TrimSpace(uuid)] + m.nativeQuotaMu.RUnlock() + return state +} + +// acquireNativeClientConnection enforces the DB-backed max_conns policy across +// every native inbound and transport. The returned release function is safe to +// call more than once and keeps runtime/DB online counters in sync. +func (m *XrayManager) acquireNativeClientConnection(uuid, email string, closers ...io.Closer) (func(), *xrayNativeQuotaState, bool) { + state := m.nativeQuotaState(uuid) + var closer io.Closer + if len(closers) > 0 { + closer = closers[0] + } + if state != nil { + state.mu.Lock() + if reason := nativeClientAccessDeniedLocked(state); reason != "" { + state.mu.Unlock() + xrayLogf("native xray: rejected user %s: %s", email, reason) + return nil, state, false + } + if state.maxConns > 0 && state.activeConns >= state.maxConns { + limit := state.maxConns + state.mu.Unlock() + logNativeClientLimitRejection(email, limit) + return nil, state, false + } + state.activeConns++ + if closer != nil { + if state.connections == nil { + state.connections = make(map[io.Closer]struct{}) + } + state.connections[closer] = struct{}{} + } + state.mu.Unlock() + } + + m.recordNativeConnect(uuid, email, state) + var once sync.Once + return func() { + once.Do(func() { + if state != nil { + state.mu.Lock() + if closer != nil { + delete(state.connections, closer) + } + if state.activeConns > 0 { + state.activeConns-- + } + state.mu.Unlock() + } + m.recordNativeDisconnect(uuid, email, state) + }) + }, state, true +} + +func closeNativeClientConnections(state *xrayNativeQuotaState) { + if state == nil { + return + } + state.mu.Lock() + closers := make([]io.Closer, 0, len(state.connections)) + for closer := range state.connections { + closers = append(closers, closer) + } + state.mu.Unlock() + for _, closer := range closers { + _ = closer.Close() + } +} + +func (m *XrayManager) disconnectNativeClient(uuid string) { + closeNativeClientConnections(m.nativeQuotaState(uuid)) +} + +func (m *XrayManager) nativeClientAccessDenied(uuid string) string { + state := m.nativeQuotaState(uuid) + if state == nil { + return "" + } + state.mu.Lock() + reason := nativeClientAccessDeniedLocked(state) + state.mu.Unlock() + return reason +} + +func nativeClientAccessDeniedLocked(state *xrayNativeQuotaState) string { + if state.hasExpiry && !state.expiresAt.After(time.Now()) { + return "expired" + } + if state.owner != "" { + if err := ownerIsActive(state.owner); err != nil { + return "owner suspended or expired" + } + } + if state.quotaBytes > 0 && normalizeQuotaAction(state.action) == quotaActionBlock && state.usedBytes >= state.quotaBytes { + return "data quota exceeded" + } + return "" +} + +func (m *XrayManager) nativeQuotaBlocked(uuid string) bool { + return nativeQuotaStateBlocked(m.nativeQuotaState(uuid)) +} + +func nativeQuotaStateBlocked(state *xrayNativeQuotaState) bool { + if state == nil { + return false + } + state.mu.Lock() + defer state.mu.Unlock() + return state.quotaBytes > 0 && normalizeQuotaAction(state.action) == quotaActionBlock && state.usedBytes >= state.quotaBytes +} + +func (m *XrayManager) reserveNativeQuota(state *xrayNativeQuotaState, requested int) (allowed int, limiter *rate.Limiter, stopAfter bool) { + if requested <= 0 { + return 0, nil, false + } + if state == nil { + return requested, nil, false + } + state.mu.Lock() + defer state.mu.Unlock() + + n := int64(requested) + if state.quotaBytes <= 0 { + state.usedBytes += n + return requested, nil, false + } + if normalizeQuotaAction(state.action) == quotaActionThrottle { + previous := state.usedBytes + state.usedBytes += n + if previous+n > state.quotaBytes { + if state.limiter == nil { + bps := mbpsToBytesPerSec(quotaThrottleMbpsOrDefault(state.throttleMbps)) + burst := int(bps) + if burst < copyBufSize { + burst = copyBufSize + } + state.limiter = rate.NewLimiter(rate.Limit(bps), burst) + } + return requested, state.limiter, false + } + return requested, nil, false + } + + remaining := state.quotaBytes - state.usedBytes + if remaining <= 0 { + return 0, nil, true + } + take := n + if take > remaining { + take = remaining + } + state.usedBytes += take + return int(take), nil, take < n +} + +func (m *XrayManager) finishNativeQuotaReservation(state *xrayNativeQuotaState, reserved, written int) { + if reserved <= 0 || written >= reserved { + return + } + if written < 0 { + written = 0 + } + if state == nil { + return + } + state.mu.Lock() + state.usedBytes -= int64(reserved - written) + if state.usedBytes < 0 { + state.usedBytes = 0 + } + state.mu.Unlock() +} + +type xrayQuotaMeteredWriter struct { + w io.Writer + meter *trafficMeter + ctx context.Context +} + +func (mw xrayQuotaMeteredWriter) Write(p []byte) (int, error) { + if mw.meter == nil { + return mw.w.Write(p) + } + state := mw.meter.state + if state != nil { + state.trafficMu.RLock() + defer state.trafficMu.RUnlock() + } + allowed, limiter, stopAfter := xrayMgr.reserveNativeQuota(state, len(p)) + if allowed <= 0 { + return 0, errDataQuotaExceeded + } + if limiter != nil { + ctx := mw.ctx + if ctx == nil { + ctx = context.Background() + } + if err := limiter.WaitN(ctx, allowed); err != nil { + xrayMgr.finishNativeQuotaReservation(state, allowed, 0) + return 0, err + } + } + n, err := mw.w.Write(p[:allowed]) + xrayMgr.finishNativeQuotaReservation(state, allowed, n) + if n > 0 { + mw.meter.add(n) + } + if err != nil { + return n, err + } + if stopAfter || allowed < len(p) || nativeQuotaStateBlocked(state) { + return n, errDataQuotaExceeded + } + return n, nil +} + +type nativePacketQuotaReservation struct { + meter *trafficMeter + state *xrayNativeQuotaState + limiter *rate.Limiter + reserved int + finished bool +} + +func reserveNativePacketQuota(meter *trafficMeter, n int) (nativePacketQuotaReservation, error) { + if meter == nil || n <= 0 { + return nativePacketQuotaReservation{}, nil + } + state := meter.state + if state != nil { + state.trafficMu.RLock() + } + allowed, limiter, stopAfter := xrayMgr.reserveNativeQuota(state, n) + if allowed != n || stopAfter { + if allowed > 0 { + xrayMgr.finishNativeQuotaReservation(state, allowed, 0) + } + if state != nil { + state.trafficMu.RUnlock() + } + return nativePacketQuotaReservation{}, errDataQuotaExceeded + } + return nativePacketQuotaReservation{ + meter: meter, + state: state, + limiter: limiter, + reserved: n, + }, nil +} + +func (r *nativePacketQuotaReservation) wait(ctx context.Context) error { + if r == nil || r.finished || r.limiter == nil || r.reserved <= 0 { + return nil + } + if err := waitNativeRate(ctx, r.limiter, r.reserved); err != nil { + r.finish(0) + return err + } + return nil +} + +func (r *nativePacketQuotaReservation) finish(written int) { + if r == nil || r.finished { + return + } + r.finished = true + if r.meter == nil || r.reserved <= 0 { + if r.state != nil { + r.state.trafficMu.RUnlock() + } + return + } + xrayMgr.finishNativeQuotaReservation(r.state, r.reserved, written) + if written > 0 { + r.meter.add(written) + } + if r.state != nil { + r.state.trafficMu.RUnlock() + } +} diff --git a/xray_shared_port.go b/xray_shared_port.go new file mode 100644 index 0000000..26392ad --- /dev/null +++ b/xray_shared_port.go @@ -0,0 +1,167 @@ +package main + +// Shared native Xray HTTP transports are handed off before the public proxy's +// HTTP-injection cleanup writes its unsolicited SSH response. TLS is terminated +// by the panel listener, so the Xray inbound itself must use security "none". + +import ( + "bufio" + "bytes" + "fmt" + "net" + "strings" + "sync" + "time" +) + +type sharedXrayRouter struct { + ws map[string]*nativeInbound + xhttp *nativeXHTTPListener + httpListener *sharedXrayListener + listeners []net.Listener +} + +type sharedXrayListener struct { + conns chan net.Conn + done chan struct{} + once sync.Once +} + +func (l *sharedXrayListener) Accept() (net.Conn, error) { + select { + case <-l.done: + return nil, net.ErrClosed + case c := <-l.conns: + return c, nil + } +} +func (l *sharedXrayListener) Close() error { l.once.Do(func() { close(l.done) }); return nil } +func (l *sharedXrayListener) Addr() net.Addr { return &net.TCPAddr{} } + +func sharedXrayPath(path string) (string, error) { + if path == "" || path == "/" || !strings.HasPrefix(path, "/") || + strings.ContainsAny(path, "?#%\\ \t\r\n") || strings.Contains(path, "//") || + strings.Contains(path, "/./") || strings.Contains(path, "/../") || + strings.HasSuffix(path, "/.") || strings.HasSuffix(path, "/..") { + return "", fmt.Errorf("shared Xray path must be a distinct absolute path such as /c1") + } + return strings.TrimSuffix(path, "/"), nil +} + +func validateSharedXrayInbound(in nativeInboundJSON) error { + network := strings.ToLower(firstNonEmpty(in.StreamSettings.Network, "tcp")) + if network != "ws" && network != "websocket" && network != "xhttp" && network != "splithttp" { + return fmt.Errorf("shared Xray inbound %q requires WebSocket or XHTTP", in.Tag) + } + security := strings.ToLower(strings.TrimSpace(in.StreamSettings.Security)) + if security != "" && security != "none" { + return fmt.Errorf("shared Xray inbound %q must use security none; the DragonCoreSSH TLS listener terminates TLS", in.Tag) + } + path := in.StreamSettings.WSSettings.Path + if network == "xhttp" || network == "splithttp" { + path = mergeNativeXHTTPSettings(in.StreamSettings.XHTTPSettings, in.StreamSettings.SplitHTTPSettings).Path + } + if _, err := sharedXrayPath(path); err != nil { + return fmt.Errorf("inbound %q: %w", in.Tag, err) + } + return nil +} + +func newSharedXrayRouter(inbounds []*nativeInbound) (*sharedXrayRouter, error) { + r := &sharedXrayRouter{ws: make(map[string]*nativeInbound)} + var httpInbounds []*nativeInbound + paths := map[string]string{} + for _, ib := range inbounds { + if !ib.sharedPort { continue } + path, err := sharedXrayPath(ib.path) + if err != nil { return nil, fmt.Errorf("inbound %q: %w", ib.tag, err) } + for prior, tag := range paths { + if path == prior || strings.HasPrefix(path, prior+"/") || strings.HasPrefix(prior, path+"/") { + return nil, fmt.Errorf("shared Xray paths %s (%s) and %s (%s) overlap", prior, tag, path, ib.tag) + } + } + paths[path] = ib.tag + if ib.isXHTTP() { httpInbounds = append(httpInbounds, ib) } else { r.ws[path] = ib } + } + if len(paths) == 0 { return nil, nil } + if len(httpInbounds) > 0 { + group, err := newNativeXHTTPListener("DragonCoreSSH public ports", httpInbounds) + if err != nil { return nil, err } + r.xhttp = group + r.httpListener = &sharedXrayListener{conns: make(chan net.Conn, 128), done: make(chan struct{})} + r.listeners = []net.Listener{r.httpListener} + } + return r, nil +} + +func nativeSharedEnabled() bool { return nativeXray.shared.Load() != nil } + +func (r *sharedXrayRouter) takeHTTP(conn net.Conn, reader *bufio.Reader) { + select { + case <-r.httpListener.done: + _ = conn.Close() + case r.httpListener.conns <- &bufferedConn{Conn: conn, r: reader}: + default: + _ = conn.Close() + } +} + +// nativeTakeSharedConn only runs before the public SSH proxy writes a response, +// or after the panel TLS handshake. Peek leaves every byte intact for the +// Xray transport and for normal SSH/injection clients on a negative match. +func nativeTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, bool) { + router := nativeXray.shared.Load() + if router == nil { return reader, false } + if reader == nil { reader = bufio.NewReaderSize(conn, 16*1024) } + // SSH may wait for the server banner. Bound the first-byte wait so adding + // Xray sharing does not stall every ordinary SSH connection for three seconds. + _ = conn.SetReadDeadline(time.Now().Add(time.Second)) + defer conn.SetReadDeadline(time.Time{}) + first, err := reader.Peek(1) + if err != nil || len(first) == 0 || (first[0] != 'G' && first[0] != 'P' && first[0] != 'O' && first[0] != 'D') { + return reader, false + } + _ = conn.SetReadDeadline(time.Now().Add(tunnelSniffTimeout)) + if first[0] == 'P' && router.xhttp != nil { + prefix, err := reader.Peek(3) + if err == nil && string(prefix) == "PRI" { + if preface, err := reader.Peek(len("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")); err == nil && + string(preface) == "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" { + router.takeHTTP(conn, reader) + return reader, true + } + } + } + // Require a complete bounded HTTP header before trusting a path. An SSH + // payload that happens to start with 'G' must still fall through untouched. + var header []byte + for n := 4; n <= 16*1024; n++ { + peek, e := reader.Peek(n) + if len(peek) == n && bytes.Equal(peek[n-4:], []byte("\r\n\r\n")) { header = peek; break } + if e != nil { return reader, false } + } + if len(header) == 0 { return reader, false } + lineEnd := bytes.Index(header, []byte("\r\n")) + if lineEnd < 0 { return reader, false } + parts := strings.SplitN(string(header[:lineEnd]), " ", 3) + if len(parts) != 3 || !strings.HasPrefix(parts[2], "HTTP/1.") { return reader, false } + method := parts[0] + if method != "GET" && method != "POST" && method != "OPTIONS" && method != "HEAD" { return reader, false } + path := strings.SplitN(parts[1], "?", 2)[0] + path = strings.TrimSuffix(path, "/") + if ib := router.ws[path]; ib != nil && method == "GET" && + bytes.Contains(bytes.ToLower(header), []byte("upgrade: websocket")) { + counted, ok := waitWrapTrackedNativeTransportConn(&bufferedConn{Conn: conn, r: reader}) + if !ok { return reader, true } + xrayGo("native xray shared WebSocket", func() { ib.serve(counted) }) + return reader, true + } + if router.xhttp != nil { + for _, ib := range router.xhttp.inbounds { + if _, ok := ib.matchXHTTPPath(path); !ok { continue } + router.takeHTTP(conn, reader) + return reader, true + } + } + return reader, false +} diff --git a/xray_shared_port_test.go b/xray_shared_port_test.go new file mode 100644 index 0000000..c475ddf --- /dev/null +++ b/xray_shared_port_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "io" + "net" + "strings" + "testing" + "time" +) + +func TestSharedXrayPathsRequireExplicitNonRootHTTPTransport(t *testing.T) { + for _, body := range []string{ + `{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"tcp"}}`, + `{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","wsSettings":{"path":"/"}}}`, + `{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","security":"tls","wsSettings":{"path":"/c1"}}}`, + } { + if err := validateNativeInboundBindings([]byte(`{"inbounds":[` + body + `]}`)); err == nil { + t.Fatalf("accepted invalid shared inbound: %s", body) + } + } + valid := []byte(`{"inbounds":[{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","wsSettings":{"path":"/c1"}}},{"tag":"b","protocol":"vmess","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/c2"}}}]}`) + if err := validateNativeInboundBindings(valid); err != nil { t.Fatal(err) } + overlap := strings.Replace(string(valid), "/c2", "/c1/nested", 1) + if err := validateNativeInboundBindings([]byte(overlap)); err == nil { t.Fatal("accepted overlapping shared paths") } +} + +func TestSharedXraySniffPreservesHTTPBytes(t *testing.T) { + ib := &nativeInbound{tag: "x", transport: "xhttp", path: "/c1", xhttpSessions: make(map[string]*nativeXHTTPSession)} + router, err := newSharedXrayRouter([]*nativeInbound{ib}) + if err != nil { t.Fatal(err) } + nativeXray.shared.Store(router) + defer nativeXray.shared.Store(nil) + defer router.httpListener.Close() + request := "OPTIONS /c1/sid HTTP/1.1\r\nHost: example.test\r\n\r\n" + client, server := net.Pipe() + defer client.Close() + defer server.Close() + done := make(chan bool, 1) + go func() { _, taken := nativeTakeSharedConn(server, nil); done <- taken }() + if _, err := io.WriteString(client, request); err != nil { t.Fatal(err) } + select { + case taken := <-done: + if !taken { t.Fatal("shared path not routed") } + case <-time.After(2*time.Second): t.Fatal("shared sniff stalled") + } + select { + case routed := <-router.httpListener.conns: + buf := make([]byte, len(request)) + if _, err := io.ReadFull(routed, buf); err != nil { t.Fatal(err) } + if string(buf) != request { t.Fatalf("routed bytes changed: %q", buf) } + case <-time.After(2*time.Second): t.Fatal("XHTTP connection not queued") + } +} diff --git a/xray_vmess.go b/xray_vmess.go new file mode 100644 index 0000000..aa81088 --- /dev/null +++ b/xray_vmess.go @@ -0,0 +1,737 @@ +package main + +// Pure-Go VMess (AEAD) server, part of the in-process Xray emulator. +// +// This implements the modern "VMess AEAD" protocol (alterId = 0) exactly as +// spoken by current Xray/v2ray clients: AEAD-authenticated request header, +// AES-128-GCM / ChaCha20-Poly1305 chunked body with SHAKE-masked lengths, +// optional global padding and authenticated length, and the AEAD response +// header + body. Byte offsets, KDF labels and orderings follow the v2fly/xray +// reference (proxy/vmess/{aead,encoding}). Legacy MD5-auth VMess (alterId > 0) +// is intentionally not supported. +// +// TCP and UDP commands are served. Mux is intentionally not supported in the +// native emulator yet. + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/md5" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "hash" + "hash/crc32" + "hash/fnv" + "io" + "log" + "net" + "sync" + "time" + + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/sha3" +) + +// ---------- constants ---------- + +const vmessCmdKeyMagic = "c48619fe-8f02-49e0-b9e9-edf763e17e21" + +const ( + kdfSaltVMessAEADKDF = "VMess AEAD KDF" + + kdfLabelAuthIDEncryptionKey = "AES Auth ID Encryption" + + kdfLabelReqHeaderLenKey = "VMess Header AEAD Key_Length" + kdfLabelReqHeaderLenIV = "VMess Header AEAD Nonce_Length" + kdfLabelReqHeaderKey = "VMess Header AEAD Key" + kdfLabelReqHeaderIV = "VMess Header AEAD Nonce" + + kdfLabelRespHeaderLenKey = "AEAD Resp Header Len Key" + kdfLabelRespHeaderLenIV = "AEAD Resp Header Len IV" + kdfLabelRespHeaderKey = "AEAD Resp Header Key" + kdfLabelRespHeaderIV = "AEAD Resp Header IV" + + kdfLabelAuthLen = "auth_len" +) + +// VMess request option flags (header byte 34). +const ( + vmessOptChunkStream = 0x01 + vmessOptChunkMasking = 0x04 + vmessOptGlobalPadding = 0x08 + vmessOptAuthenticatedLength = 0x10 +) + +// VMess security types (low nibble of header byte 35). +const ( + vmessSecAES128GCM = 3 + vmessSecChaCha20Poly1305 = 4 + vmessSecNone = 5 +) + +// VMess commands (header byte 37). +const ( + vmessCmdTCP = 1 + vmessCmdUDP = 2 + vmessCmdMux = 3 +) + +const vmessTimeWindowSeconds = 120 + +// ---------- KDF ("VMess AEAD KDF", nested HMAC-SHA256) ---------- + +type hmacCreator struct { + parent *hmacCreator + value []byte +} + +func newHMAC(f func() hash.Hash, key []byte) hash.Hash { + return hmac.New(f, key) +} + +func (h *hmacCreator) create() hash.Hash { + if h.parent == nil { + return newHMAC(sha256.New, h.value) + } + return newHMAC(h.parent.create, h.value) +} + +func vmessKDF(key []byte, path ...string) []byte { + c := &hmacCreator{value: []byte(kdfSaltVMessAEADKDF)} + for _, p := range path { + c = &hmacCreator{value: []byte(p), parent: c} + } + h := c.create() + h.Write(key) + return h.Sum(nil) +} + +func vmessKDF16(key []byte, path ...string) []byte { + return vmessKDF(key, path...)[:16] +} + +// ---------- command key / crypto helpers ---------- + +func vmessCmdKey(uuid [16]byte) [16]byte { + h := md5.New() + h.Write(uuid[:]) + h.Write([]byte(vmessCmdKeyMagic)) + var out [16]byte + copy(out[:], h.Sum(nil)) + return out +} + +func newAESGCM(key []byte) cipher.AEAD { + block, err := aes.NewCipher(key) + if err != nil { + panic(err) // only happens on wrong key length — a programmer error + } + gcm, err := cipher.NewGCM(block) + if err != nil { + panic(err) + } + return gcm +} + +// vmessChaChaKey expands a 16-byte key into the 32-byte ChaCha20 key VMess uses: +// MD5(key) || MD5(MD5(key)). +func vmessChaChaKey(key []byte) []byte { + h1 := md5.Sum(key) + h2 := md5.Sum(h1[:]) + out := make([]byte, 32) + copy(out[0:16], h1[:]) + copy(out[16:32], h2[:]) + return out +} + +func absInt64(v int64) int64 { + if v < 0 { + return -v + } + return v +} + +func shakeNext(s sha3.ShakeHash) uint16 { + var b [2]byte + _, _ = s.Read(b[:]) + return binary.BigEndian.Uint16(b[:]) +} + +// ---------- auth ID matching ---------- + +// matchVMess tries every VMess client's auth-ID cipher against the 16-byte +// auth ID, returning the client whose key decrypts to a CRC-valid, in-window +// timestamp. This is O(clients) AES blocks per connection. +func (ib *nativeInbound) matchVMess(authid [16]byte, now int64) *nativeXrayClient { + ib.clientMu.RLock() + defer ib.clientMu.RUnlock() + for _, c := range ib.clientsByID { + if c.authIDCipher == nil { + continue + } + var dec [16]byte + c.authIDCipher.Decrypt(dec[:], authid[:]) + if crc32.ChecksumIEEE(dec[0:12]) != binary.BigEndian.Uint32(dec[12:16]) { + continue + } + t := int64(binary.BigEndian.Uint64(dec[0:8])) + if t < 0 || absInt64(t-now) > vmessTimeWindowSeconds { + continue + } + return c + } + return nil +} + +// ---------- request header ---------- + +type vmessRequest struct { + bodyIV [16]byte + bodyKey [16]byte + respV byte + option byte + security byte + command byte + host string + port uint16 +} + +// openVMessHeader reads and decrypts the AEAD request header from r, given the +// user's command key and the already-read 16-byte auth ID. r must be positioned +// immediately after the auth ID. +func openVMessHeader(cmdKey [16]byte, authid [16]byte, r io.Reader) ([]byte, error) { + var lenBlock [18]byte // 2-byte length + 16-byte tag + if _, err := io.ReadFull(r, lenBlock[:]); err != nil { + return nil, err + } + var connNonce [8]byte + if _, err := io.ReadFull(r, connNonce[:]); err != nil { + return nil, err + } + + aid := string(authid[:]) + cn := string(connNonce[:]) + + lenGCM := newAESGCM(vmessKDF16(cmdKey[:], kdfLabelReqHeaderLenKey, aid, cn)) + lenNonce := vmessKDF(cmdKey[:], kdfLabelReqHeaderLenIV, aid, cn)[:12] + lenPlain, err := lenGCM.Open(nil, lenNonce, lenBlock[:], authid[:]) + if err != nil { + return nil, fmt.Errorf("vmess: header length decrypt: %w", err) + } + headerLen := int(binary.BigEndian.Uint16(lenPlain)) + if headerLen < 38 || headerLen > 512 { + return nil, fmt.Errorf("vmess: implausible header length %d", headerLen) + } + + payload := make([]byte, headerLen+16) + if _, err := io.ReadFull(r, payload); err != nil { + return nil, err + } + payGCM := newAESGCM(vmessKDF16(cmdKey[:], kdfLabelReqHeaderKey, aid, cn)) + payNonce := vmessKDF(cmdKey[:], kdfLabelReqHeaderIV, aid, cn)[:12] + header, err := payGCM.Open(nil, payNonce, payload, authid[:]) + if err != nil { + return nil, fmt.Errorf("vmess: header payload decrypt: %w", err) + } + return header, nil +} + +// parseVMessHeader parses the decrypted request header plaintext. +func parseVMessHeader(h []byte) (vmessRequest, error) { + var req vmessRequest + if len(h) < 40 { + return req, errors.New("vmess: header too short") + } + if h[0] != 1 { + return req, fmt.Errorf("vmess: unsupported version %d", h[0]) + } + copy(req.bodyIV[:], h[1:17]) + copy(req.bodyKey[:], h[17:33]) + req.respV = h[33] + req.option = h[34] + req.security = h[35] & 0x0f + paddingLen := int(h[35] >> 4) + req.command = h[37] + req.port = binary.BigEndian.Uint16(h[38:40]) + + host, next, err := parseVMessAddress(h, 40) + if err != nil { + return req, err + } + req.host = host + + if next+paddingLen+4 != len(h) { + return req, fmt.Errorf("vmess: header length mismatch (addr end %d + pad %d + 4 != %d)", next, paddingLen, len(h)) + } + + f := fnv.New32a() + f.Write(h[:len(h)-4]) + if binary.BigEndian.Uint32(h[len(h)-4:]) != f.Sum32() { + return req, errors.New("vmess: header checksum mismatch") + } + return req, nil +} + +func parseVMessAddress(h []byte, off int) (host string, next int, err error) { + if off >= len(h) { + return "", 0, io.ErrUnexpectedEOF + } + atyp := h[off] + off++ + switch atyp { + case atypIPv4: + if off+4 > len(h) { + return "", 0, io.ErrUnexpectedEOF + } + host = net.IP(h[off : off+4]).String() + off += 4 + case atypIPv6: + if off+16 > len(h) { + return "", 0, io.ErrUnexpectedEOF + } + host = net.IP(h[off : off+16]).String() + off += 16 + case atypDomain: + if off >= len(h) { + return "", 0, io.ErrUnexpectedEOF + } + l := int(h[off]) + off++ + if off+l > len(h) { + return "", 0, io.ErrUnexpectedEOF + } + host = string(h[off : off+l]) + off += l + default: + return "", 0, fmt.Errorf("vmess: unknown address type %d", atyp) + } + return host, off, nil +} + +// ---------- response header ---------- + +func writeVMessResponseHeader(w io.Writer, respBodyKey, respBodyIV [16]byte, respV byte) error { + header := []byte{respV, 0, 0, 0} // V echo, option 0, command 0, command-data-length 0 + + lenGCM := newAESGCM(vmessKDF16(respBodyKey[:], kdfLabelRespHeaderLenKey)) + lenNonce := vmessKDF(respBodyIV[:], kdfLabelRespHeaderLenIV)[:12] + var lenPlain [2]byte + binary.BigEndian.PutUint16(lenPlain[:], uint16(len(header))) + lenSealed := lenGCM.Seal(nil, lenNonce, lenPlain[:], nil) // AAD nil + + payGCM := newAESGCM(vmessKDF16(respBodyKey[:], kdfLabelRespHeaderKey)) + payNonce := vmessKDF(respBodyIV[:], kdfLabelRespHeaderIV)[:12] + paySealed := payGCM.Seal(nil, payNonce, header, nil) // AAD nil + + out := make([]byte, 0, len(lenSealed)+len(paySealed)) + out = append(out, lenSealed...) + out = append(out, paySealed...) + _, err := w.Write(out) + return err +} + +// ---------- authenticated-length size parser ---------- + +// vmessAuthLen encodes/decodes the 2-byte chunk length as an AEAD-sealed field +// (option AuthenticatedLength). It always derives its key from the *request* +// body key/IV, in both directions, per the reference. +type vmessAuthLen struct { + aead cipher.AEAD + count uint16 + ivTail [10]byte + nonce [12]byte +} + +func newVMessAuthLen(reqBodyKey, reqBodyIV [16]byte, chacha bool) *vmessAuthLen { + keyMat := vmessKDF16(reqBodyKey[:], kdfLabelAuthLen) + var aead cipher.AEAD + if chacha { + a, _ := chacha20poly1305.New(vmessChaChaKey(keyMat)) + aead = a + } else { + aead = newAESGCM(keyMat) + } + al := &vmessAuthLen{aead: aead} + copy(al.ivTail[:], reqBodyIV[2:12]) + return al +} + +func (al *vmessAuthLen) nextNonce() []byte { + binary.BigEndian.PutUint16(al.nonce[0:2], al.count) + copy(al.nonce[2:12], al.ivTail[:]) + al.count++ + return al.nonce[:12] +} + +func (al *vmessAuthLen) decode(r io.Reader) (int, error) { + var buf [18]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return 0, err + } + plain, err := al.aead.Open(nil, al.nextNonce(), buf[:], nil) + if err != nil { + return 0, fmt.Errorf("vmess: auth-len decrypt: %w", err) + } + return int(binary.BigEndian.Uint16(plain)) + 16, nil +} + +func (al *vmessAuthLen) encode(out *bytes.Buffer, size int) { + var lenPlain [2]byte + binary.BigEndian.PutUint16(lenPlain[:], uint16(size-16)) + out.Write(al.aead.Seal(nil, al.nextNonce(), lenPlain[:], nil)) +} + +// ---------- body chunk reader/writer ---------- + +const vmessMaxChunk = 64*1024 + 64 + +type vmessChunkReader struct { + r io.Reader + aead cipher.AEAD // nil for security "none" + overhead int + ivTail [10]byte + count uint16 + nonce [12]byte + shake sha3.ShakeHash // non-nil when chunk masking is enabled + authLen *vmessAuthLen // non-nil when authenticated length is enabled + globalPad bool + leftover []byte + eof bool +} + +func (cr *vmessChunkReader) nextNonce() []byte { + binary.BigEndian.PutUint16(cr.nonce[0:2], cr.count) + copy(cr.nonce[2:12], cr.ivTail[:]) + cr.count++ + return cr.nonce[:12] +} + +func (cr *vmessChunkReader) readChunk() ([]byte, error) { + // Padding length is always drawn from the SHAKE stream before the size. + pad := 0 + if cr.shake != nil && cr.globalPad { + pad = int(shakeNext(cr.shake) % 64) + } + + var size int + switch { + case cr.authLen != nil: + s, err := cr.authLen.decode(cr.r) + if err != nil { + return nil, err + } + size = s + case cr.shake != nil: + var b [2]byte + if _, err := io.ReadFull(cr.r, b[:]); err != nil { + return nil, err + } + size = int(shakeNext(cr.shake) ^ binary.BigEndian.Uint16(b[:])) + default: + var b [2]byte + if _, err := io.ReadFull(cr.r, b[:]); err != nil { + return nil, err + } + size = int(binary.BigEndian.Uint16(b[:])) + } + + // size == overhead + pad means an empty (terminating) chunk. + if size == cr.overhead+pad { + return nil, io.EOF + } + if size < cr.overhead+pad || size > vmessMaxChunk { + return nil, fmt.Errorf("vmess: bad chunk size %d", size) + } + + data := make([]byte, size) + if _, err := io.ReadFull(cr.r, data); err != nil { + return nil, err + } + sealed := data[:size-pad] // trailing pad bytes are clear-text, discarded + if cr.aead == nil { + return sealed, nil + } + plain, err := cr.aead.Open(nil, cr.nextNonce(), sealed, nil) + if err != nil { + return nil, fmt.Errorf("vmess: body decrypt: %w", err) + } + return plain, nil +} + +func (cr *vmessChunkReader) Read(p []byte) (int, error) { + for len(cr.leftover) == 0 { + if cr.eof { + return 0, io.EOF + } + chunk, err := cr.readChunk() + if err == io.EOF { + cr.eof = true + return 0, io.EOF + } + if err != nil { + return 0, err + } + cr.leftover = chunk + } + n := copy(p, cr.leftover) + cr.leftover = cr.leftover[n:] + return n, nil +} + +type vmessChunkWriter struct { + w io.Writer + aead cipher.AEAD + overhead int + ivTail [10]byte + count uint16 + nonce [12]byte + shake sha3.ShakeHash + authLen *vmessAuthLen + globalPad bool +} + +func (cw *vmessChunkWriter) nextNonce() []byte { + binary.BigEndian.PutUint16(cw.nonce[0:2], cw.count) + copy(cw.nonce[2:12], cw.ivTail[:]) + cw.count++ + return cw.nonce[:12] +} + +func (cw *vmessChunkWriter) writeChunk(p []byte) error { + var out bytes.Buffer + + pad := 0 + if cw.shake != nil && cw.globalPad { + pad = int(shakeNext(cw.shake) % 64) + } + size := len(p) + cw.overhead + pad + + switch { + case cw.authLen != nil: + cw.authLen.encode(&out, size) + case cw.shake != nil: + var b [2]byte + binary.BigEndian.PutUint16(b[:], shakeNext(cw.shake)^uint16(size)) + out.Write(b[:]) + default: + var b [2]byte + binary.BigEndian.PutUint16(b[:], uint16(size)) + out.Write(b[:]) + } + + if cw.aead != nil { + out.Write(cw.aead.Seal(nil, cw.nextNonce(), p, nil)) + } else { + out.Write(p) + } + if pad > 0 { + padBytes := make([]byte, pad) + _, _ = rand.Read(padBytes) + out.Write(padBytes) + } + _, err := cw.w.Write(out.Bytes()) + return err +} + +// ---------- vmessConn: net.Conn view of a decoded VMess session ---------- + +type nativeVMessStream interface { + net.Conn + ReadPacket() ([]byte, error) + WritePacket([]byte) error +} + +type vmessConn struct { + net.Conn + reader *vmessChunkReader + writer *vmessChunkWriter + terminateOnClose bool + closeOnce sync.Once +} + +func (c *vmessConn) Read(p []byte) (int, error) { return c.reader.Read(p) } + +// ReadPacket returns exactly one decrypted VMess body chunk. UDP-over-VMess uses +// one VMess chunk per UDP datagram, so packet handling must bypass the streamy +// Read method that can merge/split chunks. +func (c *vmessConn) ReadPacket() ([]byte, error) { return c.reader.readChunk() } + +func (c *vmessConn) WritePacket(p []byte) error { return c.writer.writeChunk(p) } + +func (c *vmessConn) Write(p []byte) (int, error) { + // Bound each chunk well under the uint16 length field. + const maxChunk = 16 * 1024 + total := 0 + for len(p) > 0 { + n := len(p) + if n > maxChunk { + n = maxChunk + } + if err := c.writer.writeChunk(p[:n]); err != nil { + return total, err + } + total += n + p = p[n:] + } + return total, nil +} + +func (c *vmessConn) Close() error { + c.closeOnce.Do(func() { + if c.terminateOnClose { + _ = c.writer.writeChunk(nil) // terminating empty chunk + } + }) + return c.Conn.Close() +} + +// vmessRawConn is used for VMess security=none when the client did not request +// ChunkStream. Xray's own server returns a raw reader/writer in that exact case; +// treating the following TLS ClientHello/HTTP bytes as a VMess chunk length makes +// real clients authenticate but then pass no data. +type vmessRawConn struct { + net.Conn +} + +func (c *vmessRawConn) ReadPacket() ([]byte, error) { + buf := make([]byte, 64*1024) + n, err := c.Conn.Read(buf) + if n > 0 { + return buf[:n], nil + } + return nil, err +} + +func (c *vmessRawConn) WritePacket(p []byte) error { + _, err := c.Conn.Write(p) + return err +} + +func newVMessConn(stream net.Conn, req vmessRequest, respBodyKey, respBodyIV [16]byte) (nativeVMessStream, error) { + chunkMask := req.option&vmessOptChunkMasking != 0 + globalPad := req.option&vmessOptGlobalPadding != 0 + authLen := req.option&vmessOptAuthenticatedLength != 0 + chacha := req.security == vmessSecChaCha20Poly1305 + + if req.security == vmessSecNone && req.option&vmessOptChunkStream == 0 { + return &vmessRawConn{Conn: stream}, nil + } + + var readAEAD, writeAEAD cipher.AEAD + overhead := 16 + switch req.security { + case vmessSecAES128GCM: + readAEAD = newAESGCM(req.bodyKey[:]) + writeAEAD = newAESGCM(respBodyKey[:]) + case vmessSecChaCha20Poly1305: + ra, _ := chacha20poly1305.New(vmessChaChaKey(req.bodyKey[:])) + wa, _ := chacha20poly1305.New(vmessChaChaKey(respBodyKey[:])) + readAEAD, writeAEAD = ra, wa + case vmessSecNone: + overhead = 0 + default: + return nil, fmt.Errorf("vmess: unsupported security %d", req.security) + } + + cr := &vmessChunkReader{r: stream, aead: readAEAD, overhead: overhead, globalPad: globalPad} + copy(cr.ivTail[:], req.bodyIV[2:12]) + cw := &vmessChunkWriter{w: stream, aead: writeAEAD, overhead: overhead, globalPad: globalPad} + copy(cw.ivTail[:], respBodyIV[2:12]) + + if chunkMask { + rs := sha3.NewShake128() + rs.Write(req.bodyIV[:]) + cr.shake = rs + ws := sha3.NewShake128() + ws.Write(respBodyIV[:]) + cw.shake = ws + } + if authLen { + cr.authLen = newVMessAuthLen(req.bodyKey, req.bodyIV, chacha) + cw.authLen = newVMessAuthLen(req.bodyKey, req.bodyIV, chacha) + } + + return &vmessConn{Conn: stream, reader: cr, writer: cw, terminateOnClose: req.option&vmessOptChunkStream != 0 || req.security != vmessSecNone}, nil +} + +// ---------- handler ---------- + +func (ib *nativeInbound) handleVMess(stream net.Conn, remote net.Addr) { + _ = stream.SetReadDeadline(time.Now().Add(30 * time.Second)) + + var authid [16]byte + if _, err := io.ReadFull(stream, authid[:]); err != nil { + return + } + client := ib.matchVMess(authid, time.Now().Unix()) + if client == nil { + logNativePreAuthRejection("native xray: inbound %q rejected unknown/expired VMess auth id from %s", ib.tag, remote) + return + } + if reason := xrayMgr.nativeClientAccessDenied(client.uuid); reason != "" { + log.Printf("native xray: inbound %q rejected VMess user %s: %s", ib.tag, client.email, reason) + return + } + + header, err := openVMessHeader(client.cmdKey, authid, stream) + if err != nil { + log.Printf("native xray: inbound %q VMess header open failed from %s: %v", ib.tag, remote, err) + return + } + req, err := parseVMessHeader(header) + if err != nil { + log.Printf("native xray: inbound %q VMess header parse failed from %s: %v", ib.tag, remote, err) + return + } + _ = stream.SetReadDeadline(time.Time{}) + + if req.command != vmessCmdTCP && req.command != vmessCmdUDP { + log.Printf("native xray: inbound %q VMess command %d not supported yet", ib.tag, req.command) + return + } + releaseConnection, quotaState, ok := xrayMgr.acquireNativeClientConnection(client.uuid, client.email, stream) + if !ok { + return + } + defer releaseConnection() + + respBodyKey := sha256.Sum256(req.bodyKey[:]) + respBodyIV := sha256.Sum256(req.bodyIV[:]) + var rk, riv [16]byte + copy(rk[:], respBodyKey[:16]) + copy(riv[:], respBodyIV[:16]) + + if err := writeVMessResponseHeader(stream, rk, riv, req.respV); err != nil { + return + } + + vc, err := newVMessConn(stream, req, rk, riv) + if err != nil { + log.Printf("native xray: inbound %q VMess codec: %v", ib.tag, err) + return + } + + switch req.command { + case vmessCmdTCP: + backend, target, err := ib.nativeDialTCP(req.host, req.port) + if err != nil { + log.Printf("native xray: inbound %q VMess TCP dial %s failed: %v", ib.tag, target, err) + return + } + log.Printf("native xray: vmess/tcp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag) + nativeTunnel(vc, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter()) + case vmessCmdUDP: + backend, target, err := ib.nativeDialUDP(req.host, req.port) + if err != nil { + log.Printf("native xray: inbound %q VMess UDP dial %s failed: %v", ib.tag, target, err) + return + } + log.Printf("native xray: vmess/udp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag) + nativeVMessUDPTunnel(vc, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter()) + } +} diff --git a/xray_xhttp.go b/xray_xhttp.go new file mode 100644 index 0000000..324429d --- /dev/null +++ b/xray_xhttp.go @@ -0,0 +1,1652 @@ +package main + +import ( + "container/heap" + "context" + "crypto/tls" + "encoding/base64" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/net/http2" + "golang.org/x/net/http2/h2c" +) + +const ( + nativeXHTTPMaxSessionIDBytes = 256 + nativeXHTTPMaxSequenceBytes = 20 + nativeXHTTPHardMaxHeaderBytes = 256 * 1024 + nativeXHTTPHardMaxPostBytes int64 = 16 * 1024 * 1024 + nativeXHTTPMaxBufferedPosts = 512 + nativeXHTTPMaxBufferedSessionBytes = 16 * 1024 * 1024 + nativeXHTTPMaxBufferedGlobalBytes = 128 * 1024 * 1024 + // Tiny/empty packet-up requests still retain queue metadata. Charge a minimum + // amount against the byte budgets so the reassembly queue can be count-unlimited + // without allowing zero-byte packets to grow the heap without bound. + nativeXHTTPMinPacketAccountingBytes int64 = 256 +) + +var ( + nativeXHTTPBufferedBytes atomic.Int64 + nativeXHTTPBufferRejected atomic.Int64 + errNativeXHTTPUploadBufferFull = errors.New("xhttp upload buffer limit reached") + nativeXHTTPMemoryWait = struct { + sync.Mutex + waiters []*nativeXHTTPMemoryWaiter + head int + queued int + }{} +) + +type nativeXHTTPMemoryWaiter struct { + bytes int64 + ready chan struct{} + granted bool +} + +const ( + xhttpPlacementPath = "path" + xhttpPlacementQuery = "query" + xhttpPlacementHeader = "header" + xhttpPlacementCookie = "cookie" + xhttpPlacementBody = "body" + xhttpPlacementAuto = "auto" +) + +// isXHTTP reports whether this inbound uses XHTTP/SplitHTTP. Xray historically +// uses both names; the panel uses "xhttp" while upstream registers "splithttp". +func (ib *nativeInbound) isXHTTP() bool { + switch strings.ToLower(ib.transport) { + case "xhttp", "splithttp": + return true + default: + return false + } +} + +func normalizeXHTTPPath(path string) string { + path = strings.TrimSpace(path) + if i := strings.Index(path, "?"); i >= 0 { + path = path[:i] + } + if path == "" || path[0] != '/' { + path = "/" + path + } + if !strings.HasSuffix(path, "/") { + path += "/" + } + return path +} + +func mergeNativeXHTTPSettings(primary, fallback nativeXHTTPSettingsJSON) nativeXHTTPSettingsJSON { + out := primary + if out.Host == "" { + out.Host = fallback.Host + } + if out.Path == "" { + out.Path = fallback.Path + } + if out.Mode == "" { + out.Mode = fallback.Mode + } + if !out.NoSSEHeader { + out.NoSSEHeader = fallback.NoSSEHeader + } + if out.SessionIDPlacement == "" { + out.SessionIDPlacement = fallback.SessionIDPlacement + } + if out.SessionIDKey == "" { + out.SessionIDKey = fallback.SessionIDKey + } + if out.SeqPlacement == "" { + out.SeqPlacement = fallback.SeqPlacement + } + if out.SeqKey == "" { + out.SeqKey = fallback.SeqKey + } + if out.UplinkDataPlacement == "" { + out.UplinkDataPlacement = fallback.UplinkDataPlacement + } + if out.UplinkDataKey == "" { + out.UplinkDataKey = fallback.UplinkDataKey + } + if out.ScMaxEachPostBytes == nil { + out.ScMaxEachPostBytes = fallback.ScMaxEachPostBytes + } + if out.ScMaxBufferedPosts == 0 { + out.ScMaxBufferedPosts = fallback.ScMaxBufferedPosts + } + if out.ServerMaxHeaderBytes == 0 { + out.ServerMaxHeaderBytes = fallback.ServerMaxHeaderBytes + } + return out +} + +func newNativeXHTTPListener(addr string, inbounds []*nativeInbound) (*nativeXHTTPListener, error) { + if len(inbounds) == 0 { + return nil, fmt.Errorf("native xray: shared XHTTP listener %s has no inbounds", addr) + } + group := &nativeXHTTPListener{addr: addr, inbounds: append([]*nativeInbound(nil), inbounds...)} + paths := make(map[string]string, len(inbounds)) + for i, ib := range group.inbounds { + if ib == nil || !ib.isXHTTP() { + return nil, fmt.Errorf("native xray: shared XHTTP listener %s contains a non-XHTTP inbound", addr) + } + ib.path = normalizeXHTTPPath(ib.path) + if previous, exists := paths[ib.path]; exists { + return nil, fmt.Errorf("native xray: XHTTP inbounds %q and %q use the same path %s on %s", previous, ib.tag, ib.path, addr) + } + paths[ib.path] = ib.tag + if size := ib.xhttpServerMaxHeaderBytes(); size > group.headerSize { + group.headerSize = size + } + if i == 0 { + group.security = ib.security + group.tlsConfig = ib.tlsConfig + continue + } + if ib.security != group.security { + return nil, fmt.Errorf("native xray: XHTTP inbounds sharing %s must use the same TLS setting", addr) + } + if group.security == "tls" && !sameNativeTLSCertificate(group.tlsConfig, ib.tlsConfig) { + return nil, fmt.Errorf("native xray: XHTTP inbounds sharing %s must use the same TLS certificate", addr) + } + } + if group.security == "tls" && group.tlsConfig == nil { + return nil, fmt.Errorf("native xray: shared XHTTP listener %s has no TLS configuration", addr) + } + return group, nil +} + +func sameNativeTLSCertificate(a, b *tls.Config) bool { + if a == nil || b == nil || len(a.Certificates) == 0 || len(b.Certificates) == 0 { + return a == b + } + ac := a.Certificates[0].Certificate + bc := b.Certificates[0].Certificate + if len(ac) == 0 || len(bc) == 0 || len(ac[0]) != len(bc[0]) { + return false + } + return string(ac[0]) == string(bc[0]) +} + +func (ib *nativeInbound) serveXHTTPListener(ln net.Listener) { + group, err := newNativeXHTTPListener(ln.Addr().String(), []*nativeInbound{ib}) + if err != nil { + xrayLogf("native xray: XHTTP listener %q rejected: %v", ib.tag, err) + return + } + group.serve(ln) +} + +func (g *nativeXHTTPListener) serve(ln net.Listener) { + defer xrayRecover(fmt.Sprintf("native xray shared XHTTP listener addr=%s", ln.Addr())) + h2s := &http2.Server{ + MaxConcurrentStreams: nativeHTTP2MaxConcurrentStreams(), + } + handler := http.Handler(g) + // Official Xray accepts plaintext HTTP/1.1 and h2c on non-TLS XHTTP + // listeners, and negotiates h2/http1 through ALPN on TLS listeners. Without + // h2c, some clients/CDNs can reach the port but the request never reaches the + // XHTTP handler, which makes the proxy look dead with no useful target logs. + if g.security != "tls" { + handler = h2c.NewHandler(g, h2s) + } + srv := &http.Server{ + Handler: handler, + ReadHeaderTimeout: 4 * time.Second, + MaxHeaderBytes: g.headerSize, + } + if g.security == "tls" && g.tlsConfig != nil { + srv.TLSConfig = g.tlsConfig + _ = http2.ConfigureServer(srv, h2s) + } + // Each path has its own session namespace and idle sweeper. + stopSweep := make(chan struct{}) + defer close(stopSweep) + for _, ib := range g.inbounds { + ib := ib + xrayGo(fmt.Sprintf("native xray XHTTP idle sweeper inbound=%q", ib.tag), func() { ib.sweepXHTTPSessions(stopSweep) }) + } + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) && !isListenerClosed(err) { + xrayLogf("native xray: shared XHTTP server on %s stopped: %v", g.addr, err) + } +} + +// ServeHTTP picks the longest configured path. This makes a root XHTTP inbound +// coexist with more specific services such as /ssh without allowing the root +// handler to steal the SSH session path. +func (g *nativeXHTTPListener) ServeHTTP(w http.ResponseWriter, r *http.Request) { + var selected *nativeInbound + selectedLen := -1 + for _, ib := range g.inbounds { + if _, ok := ib.matchXHTTPPath(r.URL.Path); ok && len(ib.path) > selectedLen { + selected = ib + selectedLen = len(ib.path) + } + } + if selected == nil { + w.WriteHeader(http.StatusNotFound) + return + } + selected.ServeHTTP(w, r) +} + +// sweepXHTTPSessions periodically evicts connected XHTTP sessions that have seen +// no traffic (in either direction) within the idle timeout. This is the safety +// net behind the per-request context watch in handleXHTTPDownload; it only ever +// touches sessions whose lastSeen has genuinely gone stale, so an active tunnel +// (which refreshes lastSeen via nativeXHTTPConn.onActivity) is never reaped. +func (ib *nativeInbound) sweepXHTTPSessions(stop <-chan struct{}) { + defer xrayRecover(fmt.Sprintf("native xray XHTTP idle sweeper inbound=%q", ib.tag)) + idle := nativeXHTTPIdleTimeout() + if idle <= 0 { + return + } + interval := idle / 4 + if interval < 15*time.Second { + interval = 15 * time.Second + } + t := time.NewTicker(interval) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + ib.reapStaleXHTTPSessions(idle) + } + } +} + +func (ib *nativeInbound) reapStaleXHTTPSessions(idle time.Duration) { + now := time.Now() + var stale []*nativeXHTTPSession + ib.xhttpMu.Lock() + for id, s := range ib.xhttpSessions { + s.mu.Lock() + connected := s.connected + last := s.lastSeen + s.mu.Unlock() + // Unconnected sessions have their own 30s reaper; only reap connected + // ones that have gone idle past the timeout. + if connected && now.Sub(last) >= idle { + delete(ib.xhttpSessions, id) + stale = append(stale, s) + } + } + ib.xhttpMu.Unlock() + for _, s := range stale { + xrayTracef("native xray: xhttp idle sweep closing session=%q inbound=%q", s.id, ib.tag) + s.close() + } +} + +func (ib *nativeInbound) xhttpServerMaxHeaderBytes() int { + if ib.xhttpMaxHeaderBytes > 0 { + if ib.xhttpMaxHeaderBytes > nativeXHTTPHardMaxHeaderBytes { + return nativeXHTTPHardMaxHeaderBytes + } + return ib.xhttpMaxHeaderBytes + } + // Xray defaults to 8192. Keep a little room for custom headers/cookies used + // by packet-up mode while still preventing unbounded memory use. + return 64 * 1024 +} + +// ServeHTTP terminates the XHTTP/SplitHTTP transport and exposes the decoded +// byte stream to the VLESS/VMess handlers as a net.Conn. +func (ib *nativeInbound) ServeHTTP(w http.ResponseWriter, r *http.Request) { + defer xrayRecover(fmt.Sprintf("native xray XHTTP request inbound=%q method=%s path=%q remote=%s", ib.tag, r.Method, r.URL.RequestURI(), r.RemoteAddr)) + // XHTTP is a VPN transport, not a web API. A single connected user keeps a + // long-lived download handler and can generate many short packet-up handlers. + // Rejecting handlers at an application request ceiling turns normal tunnel + // bursts into 429s and, through CDNs/reverse proxies, intermittent 502s. + // HTTP/2 flow control plus the bounded, cancelable upload queues below provide + // backpressure without applying website rate-limit semantics to tunnel traffic. + if !ib.isXHTTP() { + logNativePreAuthRejection("native xray: xhttp reject inbound=%q reason=not-xhttp method=%s path=%q host=%q remote=%s", ib.tag, r.Method, r.URL.RequestURI(), r.Host, r.RemoteAddr) + xhttpBadRequest(w) + return + } + if !ib.xhttpHostAllowed(r.Host) { + logNativePreAuthRejection("native xray: xhttp reject inbound=%q reason=host method=%s path=%q host=%q want=%q remote=%s", ib.tag, r.Method, r.URL.RequestURI(), r.Host, ib.xhttpHost, r.RemoteAddr) + w.WriteHeader(http.StatusNotFound) + return + } + base, ok := ib.matchXHTTPPath(r.URL.Path) + if !ok { + logNativePreAuthRejection("native xray: xhttp reject inbound=%q reason=path method=%s path=%q want=%q host=%q remote=%s", ib.tag, r.Method, r.URL.RequestURI(), ib.path, r.Host, r.RemoteAddr) + w.WriteHeader(http.StatusNotFound) + return + } + + ib.writeXHTTPCommonHeaders(w, r) + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + + releaseRequest, ok := acquireNativeXHTTPRequest() + if !ok { + logNativeLimitRejection("simultaneous XHTTP handlers", &nativeXHTTPRejected, nativeXHTTPRequestLimit()) + w.Header().Set("Retry-After", "1") + http.Error(w, "xhttp transport temporarily busy", http.StatusServiceUnavailable) + return + } + defer releaseRequest() + + sessionID, seqStr := ib.extractXHTTPMeta(r, base) + if len(sessionID) > nativeXHTTPMaxSessionIDBytes || len(seqStr) > nativeXHTTPMaxSequenceBytes { + logNativePreAuthRejection("native xray: xhttp reject inbound=%q reason=metadata-size remote=%s", ib.tag, r.RemoteAddr) + xhttpBadRequest(w) + return + } + mode := ib.normalizedXHTTPMode() + xrayTracef("native xray: xhttp request inbound=%q method=%s proto=%s path=%q host=%q session=%q seq=%q len=%d mode=%s remote=%s", ib.tag, r.Method, r.Proto, r.URL.RequestURI(), r.Host, sessionID, seqStr, r.ContentLength, mode, r.RemoteAddr) + + if sessionID == "" && mode != "" && mode != "auto" && mode != "stream-one" && mode != "stream-up" { + http.Error(w, "stream-one mode is not allowed", http.StatusBadRequest) + return + } + + isUplinkRequest := true + if r.Method == http.MethodGet { + isUplinkRequest = seqStr != "" + } + + if isUplinkRequest && sessionID != "" { // stream-up, packet-up + sess := ib.upsertXHTTPSession(w, sessionID) + if sess == nil { + return + } + if seqStr == "" { + ib.handleXHTTPStreamUpload(w, r, sess) + return + } + ib.handleXHTTPPacketUpload(w, r, sess, seqStr) + return + } + + if r.Method == http.MethodGet || sessionID == "" { // stream-down, stream-one + if sessionID != "" { + sess := ib.upsertXHTTPSession(w, sessionID) + if sess == nil { + return + } + ib.handleXHTTPDownload(w, r, sess, sessionID) + return + } + if r.Body == nil || (r.ContentLength == 0 && len(r.TransferEncoding) == 0) { + xhttpBadRequest(w) + return + } + ib.handleXHTTPStreamOne(w, r) + return + } + + w.Header().Set("Allow", "GET, POST, PUT, PATCH, OPTIONS") + w.WriteHeader(http.StatusMethodNotAllowed) +} + +func xhttpBadRequest(w http.ResponseWriter) { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) +} + +func (ib *nativeInbound) normalizedXHTTPMode() string { + mode := strings.ToLower(strings.TrimSpace(ib.xhttpMode)) + if mode == "" { + return "auto" + } + return mode +} + +func isXHTTPUploadMethod(method string) bool { + switch method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + return true + default: + return false + } +} + +func (ib *nativeInbound) xhttpHostAllowed(reqHost string) bool { + want := strings.TrimSpace(ib.xhttpHost) + if want == "" { + return true + } + for _, h := range strings.Split(want, ",") { + h = strings.TrimSpace(h) + if h == "" { + continue + } + if strings.EqualFold(reqHost, h) { + return true + } + reqBare := stripHostPort(reqHost) + wantBare := stripHostPort(h) + if strings.EqualFold(reqBare, wantBare) { + return true + } + } + return false +} + +func stripHostPort(h string) string { + h = strings.TrimSpace(h) + if h == "" { + return "" + } + if strings.HasPrefix(h, "[") { + if end := strings.Index(h, "]"); end >= 0 { + return strings.Trim(h[1:end], "[]") + } + } + if host, _, err := net.SplitHostPort(h); err == nil { + return strings.Trim(host, "[]") + } + if i := strings.LastIndex(h, ":"); i > -1 && strings.Count(h, ":") == 1 { + return h[:i] + } + return strings.Trim(h, "[]") +} + +func (ib *nativeInbound) matchXHTTPPath(reqPath string) (base string, ok bool) { + base = ib.path + if base == "" { + base = "/" + } + base = normalizeXHTTPPath(base) + if strings.HasPrefix(reqPath, base) { + return base, true + } + trimmed := strings.TrimSuffix(base, "/") + if trimmed == "" { + trimmed = "/" + } + if reqPath == trimmed { + return base, true + } + return base, false +} + +func (ib *nativeInbound) writeXHTTPCommonHeaders(w http.ResponseWriter, r *http.Request) { + origin := r.Header.Get("Origin") + if origin == "" { + w.Header().Set("Access-Control-Allow-Origin", "*") + } else { + w.Header().Set("Access-Control-Allow-Origin", origin) + } + if r.Method == http.MethodOptions { + if m := r.Header.Get("Access-Control-Request-Method"); m != "" { + w.Header().Set("Access-Control-Allow-Methods", m) + } else { + w.Header().Set("Access-Control-Allow-Methods", "*") + } + if h := r.Header.Get("Access-Control-Request-Headers"); h != "" { + w.Header().Set("Access-Control-Allow-Headers", h) + } else { + w.Header().Set("Access-Control-Allow-Headers", "*") + } + } +} + +func (ib *nativeInbound) extractXHTTPMeta(r *http.Request, base string) (sessionID, seqStr string) { + sessionPlacement := firstNonEmpty(ib.xhttpSessionPlacement, xhttpPlacementPath) + seqPlacement := firstNonEmpty(ib.xhttpSeqPlacement, xhttpPlacementPath) + sessionKey := firstNonEmpty(ib.xhttpSessionKey, defaultXHTTPMetaKey(sessionPlacement, true)) + seqKey := firstNonEmpty(ib.xhttpSeqKey, defaultXHTTPMetaKey(seqPlacement, false)) + + var parts []string + pathPart := 0 + if sessionPlacement == xhttpPlacementPath || seqPlacement == xhttpPlacementPath { + if strings.HasPrefix(r.URL.Path, base) { + parts = strings.Split(r.URL.Path[len(base):], "/") + } + } + + if sessionPlacement == xhttpPlacementPath { + if len(parts) > pathPart { + sessionID = parts[pathPart] + pathPart++ + } + } else { + sessionID = extractXHTTPValue(r, sessionPlacement, sessionKey) + } + + if seqPlacement == xhttpPlacementPath { + if len(parts) > pathPart { + seqStr = parts[pathPart] + } + } else { + seqStr = extractXHTTPValue(r, seqPlacement, seqKey) + } + return sessionID, seqStr +} + +func defaultXHTTPMetaKey(placement string, session bool) string { + switch placement { + case xhttpPlacementHeader: + if session { + return "X-Session" + } + return "X-Seq" + case xhttpPlacementCookie, xhttpPlacementQuery: + if session { + return "x_session" + } + return "x_seq" + default: + return "" + } +} + +func extractXHTTPValue(r *http.Request, placement, key string) string { + if key == "" { + return "" + } + switch placement { + case xhttpPlacementQuery: + return r.URL.Query().Get(key) + case xhttpPlacementHeader: + return r.Header.Get(key) + case xhttpPlacementCookie: + if c, err := r.Cookie(key); err == nil { + return c.Value + } + } + return "" +} + +func (ib *nativeInbound) upsertXHTTPSession(w http.ResponseWriter, id string) *nativeXHTTPSession { + ib.xhttpMu.Lock() + defer ib.xhttpMu.Unlock() + if ib.xhttpSessions == nil { + ib.xhttpSessions = make(map[string]*nativeXHTTPSession) + } + if s := ib.xhttpSessions[id]; s != nil { + s.touch() + return s + } + releaseSlot, ok := acquireNativeXHTTPSession() + if !ok { + logNativeLimitRejection("simultaneous XHTTP sessions", &nativeXHTTPRejected, nativeXHTTPSessionLimit()) + w.Header().Set("Retry-After", "1") + http.Error(w, "xhttp session capacity temporarily busy", http.StatusServiceUnavailable) + return nil + } + s := &nativeXHTTPSession{ + id: id, + queue: newNativeXHTTPUploadQueue(ib.xhttpMaxBufferedPosts, nativeXHTTPMaxBufferedSessionBytes), + done: make(chan struct{}), + connectedCh: make(chan struct{}), + lastSeen: time.Now(), + releaseSlot: releaseSlot, + } + ib.xhttpSessions[id] = s + xrayTracef("native xray: xhttp session created inbound=%q session=%q active=%d", ib.tag, id, len(ib.xhttpSessions)) + xrayGo(fmt.Sprintf("native xray XHTTP session reaper inbound=%q session=%q", ib.tag, id), func() { ib.reapUnconnectedXHTTPSession(id, s) }) + return s +} + +func (ib *nativeInbound) xhttpMaxActiveSessions() int { + return nativeXHTTPSessionLimit() +} + +func (ib *nativeInbound) reapUnconnectedXHTTPSession(id string, s *nativeXHTTPSession) { + timer := time.NewTimer(30 * time.Second) + defer timer.Stop() + select { + case <-timer.C: + s.mu.Lock() + connected := s.connected + s.mu.Unlock() + if !connected { + ib.deleteXHTTPSession(id, s) + s.close() + } + case <-s.connectedCh: + case <-s.done: + } +} + +func (ib *nativeInbound) deleteXHTTPSession(id string, s *nativeXHTTPSession) { + ib.xhttpMu.Lock() + defer ib.xhttpMu.Unlock() + if ib.xhttpSessions[id] == s { + delete(ib.xhttpSessions, id) + } +} + +func (ib *nativeInbound) closeAllXHTTPSessions() { + ib.xhttpMu.Lock() + sessions := make([]*nativeXHTTPSession, 0, len(ib.xhttpSessions)) + for id, session := range ib.xhttpSessions { + delete(ib.xhttpSessions, id) + sessions = append(sessions, session) + } + ib.xhttpMu.Unlock() + for _, session := range sessions { + session.close() + } +} + +func (ib *nativeInbound) handleXHTTPStreamUpload(w http.ResponseWriter, r *http.Request, sess *nativeXHTTPSession) { + sess.touch() + xrayTracef("native xray: xhttp stream-up inbound=%q session=%q len=%d remote=%s", ib.tag, sess.id, r.ContentLength, r.RemoteAddr) + if ib.xhttpMode != "" && ib.xhttpMode != "auto" && ib.xhttpMode != "stream-up" && ib.xhttpMode != "stream-down" { + http.Error(w, "xhttp stream-up mode is not allowed", http.StatusBadRequest) + return + } + if err := sess.queue.push(r.Context(), nativeXHTTPPacket{Reader: r.Body}, nil); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return + } + http.Error(w, err.Error(), http.StatusConflict) + return + } + w.Header().Set("X-Accel-Buffering", "no") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusOK) + flushHTTP(w) + select { + case <-r.Context().Done(): + case <-sess.done: + } +} + +func (ib *nativeInbound) handleXHTTPPacketUpload(w http.ResponseWriter, r *http.Request, sess *nativeXHTTPSession, seqStr string) { + sess.touch() + if ib.xhttpMode != "" && ib.xhttpMode != "auto" && ib.xhttpMode != "packet-up" && ib.xhttpMode != "stream-down" { + http.Error(w, "xhttp packet-up mode is not allowed", http.StatusBadRequest) + return + } + seq, err := strconv.ParseUint(seqStr, 10, 64) + if err != nil { + http.Error(w, "bad xhttp sequence", http.StatusBadRequest) + return + } + // Reserve the expected payload rather than the configured maximum. Normal + // XHTTP body uploads have a Content-Length, so small packets no longer each + // consume a full 1 MB reservation. Unknown/chunked or metadata-carried uploads + // still reserve the maximum before decoding to preserve the hard memory bound. + memory, err := acquireNativeXHTTPMemoryContext(r.Context(), ib.xhttpUploadReservationBytes(r)) + if err != nil { + // If the client/CDN canceled while waiting for backpressure, there is no + // useful HTTP error to send. Returning also releases every reservation. + return + } + defer memory.release() + payload, err := ib.readXHTTPPayload(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + memory.shrink(nativeXHTTPAccountedPacketBytes(int64(len(payload)))) + xrayTracef("native xray: xhttp packet-up inbound=%q session=%q seq=%d payload=%d remote=%s", ib.tag, sess.id, seq, len(payload), r.RemoteAddr) + if err := sess.queue.push(r.Context(), nativeXHTTPPacket{Payload: payload, Seq: seq}, memory); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return + } + if errors.Is(err, io.ErrClosedPipe) { + // A packet can race the stream-down request closing. Acknowledge the late + // upload instead of leaking an origin 500/502 into the reconnect path. + w.WriteHeader(http.StatusOK) + return + } + if errors.Is(err, errNativeXHTTPUploadBufferFull) { + http.Error(w, err.Error(), http.StatusRequestEntityTooLarge) + return + } + xrayTracef("native xray: xhttp packet-up push failed inbound=%q session=%q seq=%d: %v", ib.tag, sess.id, seq, err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if len(payload) == 0 { + w.Header().Set("Cache-Control", "no-store") + } + w.WriteHeader(http.StatusOK) +} + +func (ib *nativeInbound) readXHTTPPayload(r *http.Request) ([]byte, error) { + placement := firstNonEmpty(ib.xhttpUplinkDataPlacement, xhttpPlacementBody) + key := firstNonEmpty(ib.xhttpUplinkDataKey, "X-Data") + + var headerPayload, cookiePayload, bodyPayload []byte + var err error + if placement == xhttpPlacementAuto || placement == xhttpPlacementHeader { + headerPayload, err = readXHTTPHeaderPayload(r, key) + if err != nil { + return nil, err + } + } + if placement == xhttpPlacementAuto || placement == xhttpPlacementCookie { + cookiePayload, err = readXHTTPCookiePayload(r, key) + if err != nil { + return nil, err + } + } + if placement == xhttpPlacementAuto || placement == xhttpPlacementBody { + bodyPayload, err = ib.readXHTTPBodyPayload(r) + if err != nil { + return nil, err + } + } + + var payload []byte + switch placement { + case xhttpPlacementHeader: + payload = headerPayload + case xhttpPlacementCookie: + payload = cookiePayload + case xhttpPlacementBody: + payload = bodyPayload + case xhttpPlacementAuto: + payload = append(payload, headerPayload...) + payload = append(payload, cookiePayload...) + payload = append(payload, bodyPayload...) + default: + return nil, fmt.Errorf("unsupported xhttp uplink data placement %q", placement) + } + if int64(len(payload)) > ib.xhttpMaxPostBytes() { + return nil, fmt.Errorf("xhttp upload too large") + } + return payload, nil +} + +func readXHTTPHeaderPayload(r *http.Request, key string) ([]byte, error) { + chunks := make([]string, 0, 4) + for i := 0; ; i++ { + chunk := r.Header.Get(fmt.Sprintf("%s-%d", key, i)) + if chunk == "" { + break + } + chunks = append(chunks, chunk) + } + if len(chunks) == 0 { + return nil, nil + } + return base64.RawURLEncoding.DecodeString(strings.Join(chunks, "")) +} + +func readXHTTPCookiePayload(r *http.Request, key string) ([]byte, error) { + chunks := make([]string, 0, 4) + for i := 0; ; i++ { + cookieName := fmt.Sprintf("%s_%d", key, i) + c, err := r.Cookie(cookieName) + if err != nil { + break + } + chunks = append(chunks, c.Value) + } + if len(chunks) == 0 { + return nil, nil + } + return base64.RawURLEncoding.DecodeString(strings.Join(chunks, "")) +} + +func (ib *nativeInbound) readXHTTPBodyPayload(r *http.Request) ([]byte, error) { + maxBytes := ib.xhttpMaxPostBytes() + if r.ContentLength > maxBytes { + return nil, fmt.Errorf("xhttp upload too large") + } + payload, err := io.ReadAll(io.LimitReader(r.Body, maxBytes+1)) + if err != nil { + return nil, err + } + if int64(len(payload)) > maxBytes { + return nil, fmt.Errorf("xhttp upload too large") + } + return payload, nil +} + +func (ib *nativeInbound) xhttpMaxPostBytes() int64 { + if ib.xhttpMaxEachPostBytes > 0 { + if ib.xhttpMaxEachPostBytes > nativeXHTTPHardMaxPostBytes { + return nativeXHTTPHardMaxPostBytes + } + return ib.xhttpMaxEachPostBytes + } + return 1_000_000 +} + +// xhttpUploadReservationBytes returns a safe pre-read reservation. Body-mode +// clients normally send Content-Length, which lets thousands of small packets +// share the global budget. Header/cookie/auto and chunked bodies reserve the +// configured maximum because their decoded size is not known until parsed. +func (ib *nativeInbound) xhttpUploadReservationBytes(r *http.Request) int64 { + maxBytes := ib.xhttpMaxPostBytes() + placement := firstNonEmpty(ib.xhttpUplinkDataPlacement, xhttpPlacementBody) + if placement == xhttpPlacementBody && r.ContentLength >= 0 { + if r.ContentLength > maxBytes { + return nativeXHTTPAccountedPacketBytes(maxBytes) + } + return nativeXHTTPAccountedPacketBytes(r.ContentLength) + } + return nativeXHTTPAccountedPacketBytes(maxBytes) +} + +func nativeXHTTPAccountedPacketBytes(payloadBytes int64) int64 { + if payloadBytes < nativeXHTTPMinPacketAccountingBytes { + return nativeXHTTPMinPacketAccountingBytes + } + return payloadBytes +} + +func (ib *nativeInbound) handleXHTTPStreamOne(w http.ResponseWriter, r *http.Request) { + defer xrayRecover(fmt.Sprintf("native xray XHTTP stream-one inbound=%q remote=%s", ib.tag, r.RemoteAddr)) + xrayTracef("native xray: xhttp stream-one inbound=%q len=%d remote=%s", ib.tag, r.ContentLength, r.RemoteAddr) + w.Header().Set("X-Accel-Buffering", "no") + w.Header().Set("Cache-Control", "no-store") + if !ib.xhttpNoSSEHeader { + w.Header().Set("Content-Type", "text/event-stream") + } + w.WriteHeader(http.StatusOK) + flushHTTP(w) + + remote := remoteAddrFromHTTPRequest(r) + resp := newNativeXHTTPResponseWriter(w) + xc := &nativeXHTTPConn{ + reader: r.Body, + writer: resp, + remote: remote, + local: dummyLocalAddr(r), + onClose: func() { + resp.close() + _ = r.Body.Close() + }, + } + ib.dispatchXHTTPConn(xc, remote) + _ = xc.Close() +} + +func (ib *nativeInbound) handleXHTTPDownload(w http.ResponseWriter, r *http.Request, sess *nativeXHTTPSession, sessionID string) { + sess.touch() + defer xrayRecover(fmt.Sprintf("native xray XHTTP download inbound=%q session=%q remote=%s", ib.tag, sessionID, r.RemoteAddr)) + xrayTracef("native xray: xhttp stream-down inbound=%q session=%q proto=%s remote=%s", ib.tag, sessionID, r.Proto, r.RemoteAddr) + sess.markConnected() + defer ib.deleteXHTTPSession(sessionID, sess) + + w.Header().Set("X-Accel-Buffering", "no") + w.Header().Set("Cache-Control", "no-store") + if !ib.xhttpNoSSEHeader { + w.Header().Set("Content-Type", "text/event-stream") + } + w.WriteHeader(http.StatusOK) + flushHTTP(w) + + remote := remoteAddrFromHTTPRequest(r) + var reader io.Reader = sess.queue + resp := newNativeXHTTPResponseWriter(w) + xc := &nativeXHTTPConn{ + reader: reader, + writer: resp, + remote: remote, + local: dummyLocalAddr(r), + onActivity: sess.touch, + } + xc.onClose = func() { + resp.close() + sess.close() + } + + // When the download GET is cancelled (client gone, or a CDN closes the + // origin stream after its own idle timeout) the HTTP request context fires. + // Closing xc unblocks the tunnel's uplink reader (via sess.close -> queue + // close) and closes the backend, so handleXHTTPDownload returns and its + // deferred deleteXHTTPSession runs. Without this watch an idle tunnel whose + // client vanished silently would never be torn down. The goroutine exits on + // sess.done once the session closes for any reason. + go func() { + select { + case <-r.Context().Done(): + // The stream-down HTTP request is the lifetime owner of an XHTTP + // session. Log the actual transport cancellation so a CDN/proxy + // timeout can be distinguished from a server idle policy. + xrayTracef("native xray: xhttp stream-down ended inbound=%q session=%q remote=%s err=%v", + ib.tag, sessionID, r.RemoteAddr, r.Context().Err()) + _ = xc.Close() + case <-sess.done: + } + }() + + ib.dispatchXHTTPConn(xc, remote) + _ = xc.Close() +} + +func (ib *nativeInbound) dispatchXHTTPConn(xc net.Conn, remote net.Addr) { + xrayTracef("native xray: xhttp dispatch inbound=%q protocol=%s remote=%s", ib.tag, ib.protocol, remote) + switch ib.protocol { + case "vless": + ib.handleVLESS(xc, remote) + case "vmess": + ib.handleVMess(xc, remote) + case "ssh": + // XHTTP->SSH tunnel: the decoded stream is a raw SSH transport. Hand it to + // the same SSH handler the TLS/DNSTT listeners use so tunneled clients + // authenticate with ordinary SSH accounts. getSSHConfig() is the live, + // hot-reloadable config; it can be nil only before the SSH server is set up. + cfg := getSSHConfig() + if cfg == nil { + xrayLogf("native xray: inbound %q XHTTP->SSH has no SSH config available yet", ib.tag) + return + } + handleConn(xc, cfg) + default: + xrayLogf("native xray: inbound %q XHTTP protocol %q not supported", ib.tag, ib.protocol) + } +} + +func remoteAddrFromHTTPRequest(r *http.Request) net.Addr { + addr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr) + if err == nil { + return addr + } + return &net.TCPAddr{IP: net.IPv4zero, Port: 0} +} + +func dummyLocalAddr(r *http.Request) net.Addr { + if r.TLS != nil && r.Host != "" { + return &net.TCPAddr{IP: net.IPv4zero, Port: 443} + } + return &net.TCPAddr{IP: net.IPv4zero, Port: 80} +} + +func flushHTTP(w http.ResponseWriter) { + if f, ok := w.(http.Flusher); ok { + f.Flush() + } +} + +type nativeXHTTPSession struct { + id string + queue *nativeXHTTPUploadQueue + done chan struct{} + closeOnce sync.Once + connectedCh chan struct{} // closed once the download GET attaches + connectOnce sync.Once + mu sync.Mutex + connected bool + lastSeen time.Time + releaseSlot func() +} + +func (s *nativeXHTTPSession) touch() { + s.mu.Lock() + s.lastSeen = time.Now() + s.mu.Unlock() +} + +func (s *nativeXHTTPSession) markConnected() { + s.mu.Lock() + s.connected = true + s.lastSeen = time.Now() + s.mu.Unlock() + s.connectOnce.Do(func() { close(s.connectedCh) }) +} + +func (s *nativeXHTTPSession) close() { + s.closeOnce.Do(func() { + close(s.done) + s.queue.close() + if s.releaseSlot != nil { + s.releaseSlot() + } + }) +} + +type nativeXHTTPConn struct { + reader io.Reader + writer io.Writer + remote net.Addr + local net.Addr + + deadlineMu sync.Mutex + readDeadline time.Time + + closeOnce sync.Once + onClose func() + // onActivity, when set, is called after any successful read or write so the + // owning session's lastSeen reflects real bidirectional traffic (not just + // HTTP request arrivals). The idle sweeper relies on this to avoid reaping a + // tunnel that is actively streaming in only one direction. + onActivity func() +} + +func (c *nativeXHTTPConn) Read(p []byte) (int, error) { + if dr, ok := c.reader.(interface{ SetReadDeadline(time.Time) error }); ok { + c.deadlineMu.Lock() + d := c.readDeadline + c.deadlineMu.Unlock() + _ = dr.SetReadDeadline(d) + } + n, err := c.reader.Read(p) + if n > 0 && c.onActivity != nil { + c.onActivity() + } + return n, err +} + +func (c *nativeXHTTPConn) Write(p []byte) (int, error) { + n, err := c.writer.Write(p) + if n > 0 && c.onActivity != nil { + c.onActivity() + } + return n, err +} + +func (c *nativeXHTTPConn) Close() error { + c.closeOnce.Do(func() { + if c.onClose != nil { + c.onClose() + } + }) + return nil +} + +func (c *nativeXHTTPConn) LocalAddr() net.Addr { return c.local } +func (c *nativeXHTTPConn) RemoteAddr() net.Addr { return c.remote } + +func (c *nativeXHTTPConn) SetDeadline(t time.Time) error { + _ = c.SetReadDeadline(t) + return c.SetWriteDeadline(t) +} + +func (c *nativeXHTTPConn) SetReadDeadline(t time.Time) error { + c.deadlineMu.Lock() + c.readDeadline = t + c.deadlineMu.Unlock() + if dr, ok := c.reader.(interface{ SetReadDeadline(time.Time) error }); ok { + return dr.SetReadDeadline(t) + } + return nil +} + +func (c *nativeXHTTPConn) SetWriteDeadline(t time.Time) error { + if dw, ok := c.writer.(interface{ SetWriteDeadline(time.Time) error }); ok { + return dw.SetWriteDeadline(t) + } + return nil +} + +type nativeXHTTPResponseWriter struct { + writeMu sync.Mutex + stateMu sync.Mutex + w http.ResponseWriter + closed bool + deadline time.Time +} + +func newNativeXHTTPResponseWriter(w http.ResponseWriter) *nativeXHTTPResponseWriter { + return &nativeXHTTPResponseWriter{w: w} +} + +func (w *nativeXHTTPResponseWriter) Write(p []byte) (int, error) { + w.writeMu.Lock() + defer w.writeMu.Unlock() + + w.stateMu.Lock() + closed := w.closed + deadline := w.deadline + w.stateMu.Unlock() + if closed { + return 0, io.ErrClosedPipe + } + + safetyDeadline := time.Now().Add(nativeXHTTPWriteTimeout()) + if deadline.IsZero() || deadline.After(safetyDeadline) { + deadline = safetyDeadline + } + controller := http.NewResponseController(w.w) + if err := controller.SetWriteDeadline(deadline); err != nil && !errors.Is(err, http.ErrNotSupported) { + return 0, err + } + n, err := w.w.Write(p) + if err == nil { + if flushErr := controller.Flush(); flushErr != nil && !errors.Is(flushErr, http.ErrNotSupported) { + err = flushErr + } + } + return n, err +} + +func (w *nativeXHTTPResponseWriter) close() { + // Do not wait for writeMu: Close is commonly called by the request-context + // watcher specifically because a CDN write is stalled. Mark the writer closed + // and force the active net/http write deadline to expire so Write returns. + w.stateMu.Lock() + w.closed = true + w.stateMu.Unlock() + _ = http.NewResponseController(w.w).SetWriteDeadline(time.Now()) +} + +func (w *nativeXHTTPResponseWriter) SetWriteDeadline(t time.Time) error { + w.stateMu.Lock() + w.deadline = t + w.stateMu.Unlock() + err := http.NewResponseController(w.w).SetWriteDeadline(t) + if errors.Is(err, http.ErrNotSupported) { + return nil + } + return err +} + +// nativeXHTTPMemoryLease reserves from a process-wide byte budget before a +// packet-up handler allocates its payload. The same lease is transferred to the +// session queue, so active request bodies and queued reassembly data share one +// hard ceiling instead of each having an independent amplification window. +type nativeXHTTPMemoryLease struct { + bytes int64 +} + +func acquireNativeXHTTPMemory(n int64) (*nativeXHTTPMemoryLease, bool) { + if n <= 0 { + return &nativeXHTTPMemoryLease{}, true + } + nativeXHTTPMemoryWait.Lock() + defer nativeXHTTPMemoryWait.Unlock() + current := nativeXHTTPBufferedBytes.Load() + if nativeXHTTPMemoryWait.queued != 0 || current > nativeXHTTPMaxBufferedGlobalBytes-n { + logNativeLimitRejection("XHTTP buffered upload bytes", &nativeXHTTPBufferRejected, nativeXHTTPMaxBufferedGlobalBytes) + return nil, false + } + nativeXHTTPBufferedBytes.Store(current + n) + return &nativeXHTTPMemoryLease{bytes: n}, true +} + +// acquireNativeXHTTPMemoryContext applies process-wide memory backpressure. +// Unlike the old fail-fast admission path, a legitimate tunnel burst waits for +// queued bytes to be consumed and remains cancelable if its HTTP request ends. +func acquireNativeXHTTPMemoryContext(ctx context.Context, n int64) (*nativeXHTTPMemoryLease, error) { + if n <= 0 { + return &nativeXHTTPMemoryLease{}, nil + } + if n > nativeXHTTPMaxBufferedGlobalBytes { + return nil, errNativeXHTTPUploadBufferFull + } + waiter := &nativeXHTTPMemoryWaiter{bytes: n, ready: make(chan struct{})} + nativeXHTTPMemoryWait.Lock() + current := nativeXHTTPBufferedBytes.Load() + if nativeXHTTPMemoryWait.queued == 0 && current <= nativeXHTTPMaxBufferedGlobalBytes-n { + nativeXHTTPBufferedBytes.Store(current + n) + nativeXHTTPMemoryWait.Unlock() + return &nativeXHTTPMemoryLease{bytes: n}, nil + } + nativeXHTTPMemoryWait.waiters = append(nativeXHTTPMemoryWait.waiters, waiter) + nativeXHTTPMemoryWait.queued++ + nativeXHTTPMemoryWait.Unlock() + + select { + case <-waiter.ready: + return &nativeXHTTPMemoryLease{bytes: n}, nil + case <-ctx.Done(): + nativeXHTTPMemoryWait.Lock() + if waiter.granted { + current := nativeXHTTPBufferedBytes.Load() - n + if current < 0 { + current = 0 + } + nativeXHTTPBufferedBytes.Store(current) + } else { + for i := nativeXHTTPMemoryWait.head; i < len(nativeXHTTPMemoryWait.waiters); i++ { + candidate := nativeXHTTPMemoryWait.waiters[i] + if candidate == waiter { + nativeXHTTPMemoryWait.waiters[i] = nil + nativeXHTTPMemoryWait.queued-- + break + } + } + } + grantNativeXHTTPMemoryWaitersLocked() + nativeXHTTPMemoryWait.Unlock() + return nil, ctx.Err() + } +} + +func releaseNativeXHTTPMemory(n int64) { + if n <= 0 { + return + } + nativeXHTTPMemoryWait.Lock() + current := nativeXHTTPBufferedBytes.Load() + next := current - n + if next < 0 { + next = 0 + } + nativeXHTTPBufferedBytes.Store(next) + grantNativeXHTTPMemoryWaitersLocked() + nativeXHTTPMemoryWait.Unlock() +} + +// grantNativeXHTTPMemoryWaitersLocked wakes only the FIFO waiters whose exact +// reservations now fit. The former broadcast channel woke every blocked HTTP +// handler after every tiny release, creating a thundering herd and sustained +// multi-core CPU usage while the 128 MB budget was full. +func grantNativeXHTTPMemoryWaitersLocked() { + for nativeXHTTPMemoryWait.queued > 0 { + for nativeXHTTPMemoryWait.head < len(nativeXHTTPMemoryWait.waiters) && + nativeXHTTPMemoryWait.waiters[nativeXHTTPMemoryWait.head] == nil { + nativeXHTTPMemoryWait.head++ + } + if nativeXHTTPMemoryWait.head >= len(nativeXHTTPMemoryWait.waiters) { + nativeXHTTPMemoryWait.waiters = nil + nativeXHTTPMemoryWait.head = 0 + nativeXHTTPMemoryWait.queued = 0 + return + } + + waiter := nativeXHTTPMemoryWait.waiters[nativeXHTTPMemoryWait.head] + current := nativeXHTTPBufferedBytes.Load() + if current > nativeXHTTPMaxBufferedGlobalBytes-waiter.bytes { + compactNativeXHTTPMemoryWaitersLocked() + return + } + nativeXHTTPMemoryWait.waiters[nativeXHTTPMemoryWait.head] = nil + nativeXHTTPMemoryWait.head++ + nativeXHTTPMemoryWait.queued-- + nativeXHTTPBufferedBytes.Store(current + waiter.bytes) + waiter.granted = true + close(waiter.ready) + } + compactNativeXHTTPMemoryWaitersLocked() +} + +func compactNativeXHTTPMemoryWaitersLocked() { + head := nativeXHTTPMemoryWait.head + if head == 0 { + return + } + if nativeXHTTPMemoryWait.queued == 0 { + nativeXHTTPMemoryWait.waiters = nil + nativeXHTTPMemoryWait.head = 0 + return + } + if head < 1024 && head*2 < len(nativeXHTTPMemoryWait.waiters) { + return + } + remaining := copy(nativeXHTTPMemoryWait.waiters, nativeXHTTPMemoryWait.waiters[head:]) + for i := remaining; i < len(nativeXHTTPMemoryWait.waiters); i++ { + nativeXHTTPMemoryWait.waiters[i] = nil + } + nativeXHTTPMemoryWait.waiters = nativeXHTTPMemoryWait.waiters[:remaining] + nativeXHTTPMemoryWait.head = 0 +} + +func (l *nativeXHTTPMemoryLease) shrink(n int64) { + if l == nil { + return + } + if n < 0 { + n = 0 + } + if n >= l.bytes { + return + } + release := l.bytes - n + l.bytes = n + releaseNativeXHTTPMemory(release) +} + +func (l *nativeXHTTPMemoryLease) release() { + if l == nil || l.bytes <= 0 { + return + } + n := l.bytes + l.bytes = 0 + releaseNativeXHTTPMemory(n) +} + +type nativeXHTTPPacket struct { + Reader io.ReadCloser + Payload []byte + Seq uint64 + accountedBytes int64 +} + +type nativeXHTTPUploadQueue struct { + pushedPackets chan nativeXHTTPPacket + maxBytes int64 + + // readMu serializes the single decoded stream reader with close-time queue + // cleanup. pushWG lets close wait until every producer that started before + // closedFlag was set has either transferred or released its memory lease. + readMu sync.Mutex + pushWG sync.WaitGroup + mu sync.Mutex + reader io.ReadCloser + readerQueued bool + heap nativeXHTTPHeap + nextSeq uint64 + readDeadline time.Time + bufferedBytes int64 + closedFlag bool + spaceChanged chan struct{} + + closed chan struct{} + closeOnce sync.Once +} + +func newNativeXHTTPUploadQueue(maxPackets int, maxBytes int64) *nativeXHTTPUploadQueue { + if maxPackets <= 0 { + maxPackets = defaultNativeXHTTPBufferedPosts + } + if maxPackets > nativeXHTTPMaxBufferedPosts { + maxPackets = nativeXHTTPMaxBufferedPosts + } + if maxBytes <= 0 || maxBytes > nativeXHTTPMaxBufferedSessionBytes { + maxBytes = nativeXHTTPMaxBufferedSessionBytes + } + return &nativeXHTTPUploadQueue{ + pushedPackets: make(chan nativeXHTTPPacket, maxPackets), + maxBytes: maxBytes, + closed: make(chan struct{}), + spaceChanged: make(chan struct{}), + } +} + +func (q *nativeXHTTPUploadQueue) beginPush() bool { + q.mu.Lock() + defer q.mu.Unlock() + if q.closedFlag { + return false + } + q.pushWG.Add(1) + return true +} + +func (q *nativeXHTTPUploadQueue) adoptPayloadMemory(ctx context.Context, memory *nativeXHTTPMemoryLease, n int64) error { + if n <= 0 { + return nil + } + if memory == nil || memory.bytes != n { + return errNativeXHTTPUploadBufferFull + } + if n > q.maxBytes { + return errNativeXHTTPUploadBufferFull + } + for { + q.mu.Lock() + if q.closedFlag { + q.mu.Unlock() + return io.ErrClosedPipe + } + if q.bufferedBytes <= q.maxBytes-n { + q.bufferedBytes += n + memory.bytes = 0 + q.mu.Unlock() + return nil + } + changed := q.spaceChanged + q.mu.Unlock() + select { + case <-changed: + case <-q.closed: + return io.ErrClosedPipe + case <-ctx.Done(): + return ctx.Err() + } + } +} + +func (q *nativeXHTTPUploadQueue) releasePayloadMemory(n int64) { + if n <= 0 { + return + } + q.mu.Lock() + release := n + if release > q.bufferedBytes { + release = q.bufferedBytes + } + q.bufferedBytes -= release + close(q.spaceChanged) + q.spaceChanged = make(chan struct{}) + q.mu.Unlock() + releaseNativeXHTTPMemory(release) +} + +func (q *nativeXHTTPUploadQueue) push(ctx context.Context, p nativeXHTTPPacket, memory *nativeXHTTPMemoryLease) error { + if !q.beginPush() { + return io.ErrClosedPipe + } + defer q.pushWG.Done() + + readerReserved := false + if p.Reader != nil { + q.mu.Lock() + if q.reader != nil || q.readerQueued || q.closedFlag { + q.mu.Unlock() + return errors.New("xhttp upload reader already exists") + } + q.readerQueued = true + readerReserved = true + q.mu.Unlock() + defer func() { + if readerReserved { + q.mu.Lock() + q.readerQueued = false + q.mu.Unlock() + } + }() + } + accountedBytes := int64(0) + if p.Reader == nil { + accountedBytes = nativeXHTTPAccountedPacketBytes(int64(len(p.Payload))) + } + if err := q.adoptPayloadMemory(ctx, memory, accountedBytes); err != nil { + return err + } + p.accountedBytes = accountedBytes + if accountedBytes > 0 { + defer func() { + if accountedBytes > 0 { + q.releasePayloadMemory(accountedBytes) + } + }() + } + select { + case q.pushedPackets <- p: + // Ownership has moved to the queue. close() waits for this producer and + // then drains/releases anything not consumed by the stream reader. + accountedBytes = 0 + readerReserved = false + return nil + case <-q.closed: + return io.ErrClosedPipe + case <-ctx.Done(): + return ctx.Err() + } +} + +func (q *nativeXHTTPUploadQueue) close() { + q.closeOnce.Do(func() { + q.mu.Lock() + q.closedFlag = true + reader := q.reader + close(q.closed) + q.mu.Unlock() + if reader != nil { + _ = reader.Close() + } + + q.pushWG.Wait() + q.readMu.Lock() + // No producers or readers can now change the queue. Drop references to + // buffered payloads promptly and return their exact byte reservation. + for { + select { + case p := <-q.pushedPackets: + if p.Reader != nil { + _ = p.Reader.Close() + } + p.Payload = nil + default: + goto drained + } + } + drained: + q.mu.Lock() + remaining := q.bufferedBytes + q.bufferedBytes = 0 + for i := range q.heap { + q.heap[i].Payload = nil + } + q.heap = nil + q.mu.Unlock() + q.readMu.Unlock() + releaseNativeXHTTPMemory(remaining) + }) +} + +func (q *nativeXHTTPUploadQueue) SetReadDeadline(t time.Time) error { + q.mu.Lock() + q.readDeadline = t + q.mu.Unlock() + return nil +} + +func (q *nativeXHTTPUploadQueue) recv() (nativeXHTTPPacket, error) { + q.mu.Lock() + d := q.readDeadline + q.mu.Unlock() + + if d.IsZero() { + select { + case p := <-q.pushedPackets: + return p, nil + case <-q.closed: + return nativeXHTTPPacket{}, io.EOF + } + } + + wait := time.Until(d) + if wait <= 0 { + return nativeXHTTPPacket{}, os.ErrDeadlineExceeded + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case p := <-q.pushedPackets: + return p, nil + case <-q.closed: + return nativeXHTTPPacket{}, io.EOF + case <-timer.C: + return nativeXHTTPPacket{}, os.ErrDeadlineExceeded + } +} + +func (q *nativeXHTTPUploadQueue) Read(b []byte) (int, error) { + q.readMu.Lock() + defer q.readMu.Unlock() + + if reader := q.loadReader(); reader != nil { + return reader.Read(b) + } + + for { + select { + case <-q.closed: + return 0, io.EOF + default: + } + + if len(q.heap) == 0 { + p, err := q.recv() + if err != nil { + return 0, err + } + if p.Reader != nil { + if !q.setReader(p.Reader) { + _ = p.Reader.Close() + return 0, io.EOF + } + return p.Reader.Read(b) + } + select { + case <-q.closed: + q.releasePayloadMemory(p.accountedBytes) + return 0, io.EOF + default: + } + heap.Push(&q.heap, p) + } + + for len(q.heap) > 0 { + packet := heap.Pop(&q.heap).(nativeXHTTPPacket) + + if packet.Seq == q.nextSeq { + if len(packet.Payload) == 0 { + q.releasePayloadMemory(packet.accountedBytes) + q.nextSeq = packet.Seq + 1 + continue + } + n := copy(b, packet.Payload) + if n < len(packet.Payload) { + q.releasePayloadMemory(int64(n)) + packet.accountedBytes -= int64(n) + packet.Payload = packet.Payload[n:] + heap.Push(&q.heap, packet) + } else { + q.releasePayloadMemory(packet.accountedBytes) + q.nextSeq = packet.Seq + 1 + } + return n, nil + } + + if packet.Seq > q.nextSeq { + heap.Push(&q.heap, packet) + p, err := q.recv() + if err != nil { + return 0, err + } + if p.Reader != nil { + _ = p.Reader.Close() + return 0, errors.New("xhttp mixed stream-up and packet-up upload") + } + heap.Push(&q.heap, p) + continue + } + + // A duplicate/late packet is discarded; release the bytes it owned. + q.releasePayloadMemory(packet.accountedBytes) + } + } +} + +func (q *nativeXHTTPUploadQueue) loadReader() io.ReadCloser { + q.mu.Lock() + defer q.mu.Unlock() + return q.reader +} + +func (q *nativeXHTTPUploadQueue) setReader(r io.ReadCloser) bool { + q.mu.Lock() + defer q.mu.Unlock() + if q.closedFlag { + return false + } + q.reader = r + return true +} + +type nativeXHTTPHeap []nativeXHTTPPacket + +func (h nativeXHTTPHeap) Len() int { return len(h) } +func (h nativeXHTTPHeap) Less(i, j int) bool { return h[i].Seq < h[j].Seq } +func (h nativeXHTTPHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *nativeXHTTPHeap) Push(x any) { *h = append(*h, x.(nativeXHTTPPacket)) } +func (h *nativeXHTTPHeap) Pop() any { + old := *h + n := len(old) + x := old[n-1] + *h = old[:n-1] + return x +}