diff --git a/README.md b/README.md index d7d8e8a..5b61331 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,18 @@ Each secret is one phone. The dashboard's **Telegram** panel adds, disables and revokes them, and a change applies immediately — a revoked phone stops working at once, with no restart. +### Tiers + +A secret carries the same tier as a SOCKS5 user, and the plan is **enforced**: +bandwidth is paced at the tier's rate, concurrent sessions are capped, and a +secret that has moved its data allowance is refused. Without this the Telegram +relay, which does not pass through the SOCKS5 pipeline, gave every phone an +unlimited pipe whatever it was on the books for. The panel shows what each phone +is using. + +Expiry is the one part of a tier that does **not** apply to a Telegram secret: it +has no end date, and a cap or a revocation is how such an account is stopped. + ### Two kinds of secret | Prefix | Transport | What a prober sees | @@ -664,8 +676,8 @@ at `/prometheus` with `basic_auth` configured. | DELETE | `/api/users/:id` | Delete user | | POST | `/api/users/:id/reset` | Reset a user's data usage | | GET | `/api/mtproto-secrets` | Telegram secrets, with the listener's bind address | -| POST | `/api/mtproto-secrets` | Add a secret; it is generated for you | -| PUT | `/api/mtproto-secrets/:id` | Relabel, or enable/disable, a secret | +| POST | `/api/mtproto-secrets` | Add a secret with its kind and tier; it is generated for you | +| PUT | `/api/mtproto-secrets/:id` | Relabel, change the tier, or enable/disable a secret | | DELETE | `/api/mtproto-secrets/:id` | Revoke a phone, effective immediately | | GET | `/api/vless-clients` | REALITY client UUIDs, and whether they can be managed | | POST | `/api/vless-clients` | Add a client; the UUID is generated if omitted | diff --git a/database.go b/database.go index bdf7be7..1178fed 100644 --- a/database.go +++ b/database.go @@ -139,6 +139,7 @@ func (s *Store) migrate() error { id INTEGER PRIMARY KEY AUTOINCREMENT, secret TEXT UNIQUE NOT NULL, label TEXT NOT NULL DEFAULT '', + tier TEXT NOT NULL DEFAULT 'unlimited', enabled INTEGER NOT NULL DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP )`, @@ -149,6 +150,16 @@ func (s *Store) migrate() error { return fmt.Errorf("exec %q: %w", q, err) } } + + // Adding a column is the one migration SQLite cannot express as + // "if not exists", so it is attempted and the duplicate-column error is the + // success case. Everything else stays in the list above, where the database + // does the work. + if _, err := s.db.Exec( + `ALTER TABLE mtproto_secrets ADD COLUMN tier TEXT NOT NULL DEFAULT 'unlimited'`, + ); err != nil && !strings.Contains(strings.ToLower(err.Error()), "duplicate column") { + return fmt.Errorf("add mtproto tier column: %w", err) + } return nil } @@ -766,17 +777,25 @@ type MtprotoSecret struct { ID int64 `json:"id"` Secret string `json:"secret"` Label string `json:"label"` + Tier string `json:"tier"` Enabled bool `json:"enabled"` CreatedAt string `json:"created_at"` } -func (s *Store) CreateMtprotoSecret(secret, label string) (*MtprotoSecret, error) { +// defaultMtprotoTier is what a secret gets when none is chosen: Telegram access +// stays reachable rather than being throttled to 1Mbps by accident. +const defaultMtprotoTier = "unlimited" + +func (s *Store) CreateMtprotoSecret(secret, label, tier string) (*MtprotoSecret, error) { secret = strings.TrimSpace(strings.ToLower(secret)) if _, err := parseMTProtoSecret(secret); err != nil { return nil, err } + if _, ok := Tiers[tier]; !ok { + tier = defaultMtprotoTier + } s.mu.Lock() - res, err := s.db.Exec("INSERT INTO mtproto_secrets (secret, label) VALUES (?, ?)", secret, label) + res, err := s.db.Exec("INSERT INTO mtproto_secrets (secret, label, tier) VALUES (?, ?, ?)", secret, label, tier) s.mu.Unlock() if err != nil { return nil, err @@ -794,8 +813,8 @@ func (s *Store) GetMtprotoSecret(id int64) (*MtprotoSecret, error) { var sec MtprotoSecret var enabled int - err := s.db.QueryRow("SELECT id, secret, label, enabled, created_at FROM mtproto_secrets WHERE id=?", id). - Scan(&sec.ID, &sec.Secret, &sec.Label, &enabled, &sec.CreatedAt) + err := s.db.QueryRow("SELECT id, secret, label, tier, enabled, created_at FROM mtproto_secrets WHERE id=?", id). + Scan(&sec.ID, &sec.Secret, &sec.Label, &sec.Tier, &enabled, &sec.CreatedAt) if err != nil { return nil, err } @@ -807,7 +826,7 @@ func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) { s.mu.Lock() defer s.mu.Unlock() - rows, err := s.db.Query("SELECT id, secret, label, enabled, created_at FROM mtproto_secrets ORDER BY id") + rows, err := s.db.Query("SELECT id, secret, label, tier, enabled, created_at FROM mtproto_secrets ORDER BY id") if err != nil { return nil, err } @@ -817,7 +836,7 @@ func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) { for rows.Next() { var sec MtprotoSecret var enabled int - if err := rows.Scan(&sec.ID, &sec.Secret, &sec.Label, &enabled, &sec.CreatedAt); err != nil { + if err := rows.Scan(&sec.ID, &sec.Secret, &sec.Label, &sec.Tier, &enabled, &sec.CreatedAt); err != nil { return nil, err } sec.Enabled = enabled != 0 @@ -826,7 +845,7 @@ func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) { return out, rows.Err() } -func (s *Store) UpdateMtprotoSecret(id int64, label *string, enabled *bool) error { +func (s *Store) UpdateMtprotoSecret(id int64, label *string, tier *string, enabled *bool) error { s.mu.Lock() defer s.mu.Unlock() @@ -835,6 +854,14 @@ func (s *Store) UpdateMtprotoSecret(id int64, label *string, enabled *bool) erro return err } } + if tier != nil { + if _, ok := Tiers[*tier]; !ok { + return fmt.Errorf("unknown tier: %s", *tier) + } + if _, err := s.db.Exec("UPDATE mtproto_secrets SET tier=? WHERE id=?", *tier, id); err != nil { + return err + } + } if enabled != nil { value := 0 if *enabled { diff --git a/faketls.go b/faketls.go index 5f3d310..b165422 100644 --- a/faketls.go +++ b/faketls.go @@ -125,7 +125,7 @@ type fakeTLSClientHello struct { // // secrets is tried in turn: the client's random is the HMAC of its own hello // under the secret it was given, so only the right key produces a match. -func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time, cloakHost string) (*fakeTLSRecordConn, *fakeTLSClientHello, error) { +func fakeTLSHandshake(conn net.Conn, secrets mtprotoGrants, now time.Time, cloakHost string) (*fakeTLSRecordConn, *fakeTLSClientHello, error) { record, raw, err := readFakeTLSRecordRaw(conn) if err != nil { return nil, nil, fmt.Errorf("read fake tls hello: %w", err) @@ -162,7 +162,7 @@ func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time, cloa // fakeTLSMatchSecret finds the secret a hello was made with. The random is an // HMAC over the hello with itself zeroed, so a mismatch is simply "no match" -- // there is nothing to give up on, and nothing leaks beyond the timing. -func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]byte, error) { +func fakeTLSMatchSecret(raw []byte, secrets mtprotoGrants, now time.Time) ([]byte, error) { const randomAt = fakeTLSServerRandomOffset if len(raw) < randomAt+32 { return nil, fmt.Errorf("ClientHello is %d bytes, too short to carry a random", len(raw)) @@ -174,11 +174,11 @@ func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]by original := append([]byte(nil), raw[randomAt:randomAt+32]...) defer copy(raw[randomAt:randomAt+32], original) - for _, secret := range secrets { + for _, grant := range secrets { for i := randomAt; i < randomAt+32; i++ { raw[i] = 0 } - mac := hmac.New(sha256.New, secret) + mac := hmac.New(sha256.New, grant.key) mac.Write(raw) want := mac.Sum(nil) @@ -191,7 +191,7 @@ func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]by if skew := now.Sub(time.Unix(int64(got), 0)); skew > fakeTLSTimeSkew || skew < -fakeTLSTimeSkew { continue } - return secret, nil + return grant.key, nil } return nil, errors.New("no configured secret matched this fake TLS hello") } diff --git a/faketls_test.go b/faketls_test.go index 15744ba..abed9c8 100644 --- a/faketls_test.go +++ b/faketls_test.go @@ -30,7 +30,7 @@ func TestFakeTLSHandshakeWithGotdClient(t *testing.T) { defer client.Close() defer server.Close() - secrets := mtprotoSecrets{secret: key} + secrets := grantsOf(t, secret, key) done := make(chan error, 1) go func() { _, info, herr := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com") @@ -69,7 +69,7 @@ func TestFakeTLSCarriesAPayloadBothWays(t *testing.T) { serverSide := make(chan *fakeTLSRecordConn, 1) go func() { - wrapped, _, err := fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com") + wrapped, _, err := fakeTLSHandshake(server, grantsOf(t, secret, key), time.Now(), "www.cloudflare.com") if err != nil { serverSide <- nil return @@ -133,7 +133,7 @@ func TestFakeTLSRefusesWrongSecret(t *testing.T) { client.SetDeadline(time.Now().Add(5 * time.Second)) go func() { - _, _, _ = fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com") + _, _, _ = fakeTLSHandshake(server, grantsOf(t, secret, key), time.Now(), "www.cloudflare.com") }() clientObf := faketls.NewFakeTLS(rand.Reader, client) @@ -160,7 +160,7 @@ func TestFakeTLSRefusesAStaleHello(t *testing.T) { // A server a day ahead of the client treats a fresh hello as stale. future := time.Now().Add(24 * time.Hour) go func() { - _, _, _ = fakeTLSHandshake(server, mtprotoSecrets{secret: key}, future, "www.cloudflare.com") + _, _, _ = fakeTLSHandshake(server, grantsOf(t, secret, key), future, "www.cloudflare.com") }() clientObf := faketls.NewFakeTLS(rand.Reader, client) @@ -179,7 +179,7 @@ func TestFakeTLSHelloDomainParsing(t *testing.T) { defer client.Close() defer server.Close() - secrets := mtprotoSecrets{secret: key} + secrets := grantsOf(t, secret, key) domains := make(chan string, 1) go func() { _, info, err := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com") @@ -262,7 +262,7 @@ func TestFakeTLSThroughTheListener(t *testing.T) { s := NewProxyServer(cfg) s.store = newTestStore(t) - if _, err := s.store.CreateMtprotoSecret(secret, "ee phone"); err != nil { + if _, err := s.store.CreateMtprotoSecret(secret, "ee phone", "unlimited"); err != nil { t.Fatalf("store secret: %v", err) } if err := s.startMTProto(nil); err != nil { @@ -302,3 +302,9 @@ func TestFakeTLSThroughTheListener(t *testing.T) { t.Errorf("echoed %q, want %q", echoed, payload) } } + +// grantsOf builds a one-entry grant set for a secret and its plan. +func grantsOf(t *testing.T, secret string, key []byte) mtprotoGrants { + t.Helper() + return mtprotoGrants{secret: mtprotoGrant{key: key, tier: Tiers[defaultMtprotoTier]}} +} diff --git a/main.go b/main.go index a8aa264..95788cc 100644 --- a/main.go +++ b/main.go @@ -582,8 +582,9 @@ type ProxyServer struct { // on every connection; the database holds them so the dashboard can manage // them across restarts. mtprotoMu sync.RWMutex - mtprotoSecrets mtprotoSecrets + mtprotoSecrets mtprotoGrants mtprotoListener net.Listener + mtprotoServer *mtprotoServer // Shutdown shutdownOnce sync.Once @@ -2003,16 +2004,29 @@ func (s *ProxyServer) adminHandler() http.Handler { s.mtprotoMu.RLock() live := len(s.mtprotoSecrets) bind := "" + var server *mtprotoServer if s.mtprotoListener != nil { bind = s.mtprotoListener.Addr().String() + server = s.mtprotoServer } s.mtprotoMu.RUnlock() + + // What each phone has used, so a plan can be seen doing something + // rather than only being configured. + usage := map[string]mtprotoSnapshot{} + if server != nil { + for _, snap := range server.mtprotoUsageSnapshot() { + usage[snap.Secret] = snap + } + } + w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]any{ "secrets": secrets, "mtproto_enabled": enabled, "bind": bind, "live_secrets": live, + "usage": usage, }) case http.MethodPost: @@ -2028,6 +2042,8 @@ func (s *ProxyServer) adminHandler() http.Handler { // The kind is per secret rather than only a server-wide default, // so both kinds can be handed out from the same running service. Kind string `json:"kind"` + // The plan this phone is held to, same tiers as the SOCKS5 port. + Tier string `json:"tier"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) @@ -2044,7 +2060,11 @@ func (s *ProxyServer) adminHandler() http.Handler { http.Error(w, "could not generate a secret: "+err.Error(), http.StatusInternalServerError) return } - created, err := s.store.CreateMtprotoSecret(secret, req.Label) + tier := defaultMtprotoTier + if req.Tier != "" { + tier = req.Tier + } + created, err := s.store.CreateMtprotoSecret(secret, req.Label, tier) if err != nil { http.Error(w, "create failed: "+err.Error(), http.StatusInternalServerError) return @@ -2084,13 +2104,14 @@ func (s *ProxyServer) adminHandler() http.Handler { case r.Method == http.MethodPut && len(parts) == 1: var req struct { Label *string `json:"label"` + Tier *string `json:"tier"` Enabled *bool `json:"enabled"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) return } - if err := s.store.UpdateMtprotoSecret(id, req.Label, req.Enabled); err != nil { + if err := s.store.UpdateMtprotoSecret(id, req.Label, req.Tier, req.Enabled); err != nil { http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) return } diff --git a/mtproto.go b/mtproto.go index cec3a61..64df3ba 100644 --- a/mtproto.go +++ b/mtproto.go @@ -3,6 +3,7 @@ package main import ( "crypto/aes" "crypto/cipher" + "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/binary" @@ -15,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" ) @@ -348,14 +350,79 @@ func mtprotoDCAddress(dc int, overrides map[int]string) string { // their hex form so the dashboard and the database speak the same identifier. type mtprotoSecrets map[string][]byte +// mtprotoGrant is one secret together with the plan it is held to. The Telegram +// relay does not pass through the SOCKS5 pipeline, so without this a phone on a +// free plan would get the same unlimited pipe as one paying for pro. +type mtprotoGrant struct { + // name is the secret as stored, which is how usage is keyed and how the + // dashboard refers to it. + name string + key []byte + tier Tier +} + +// mtprotoGrants is the live set, keyed the same way as mtprotoSecrets. +type mtprotoGrants map[string]mtprotoGrant + +// mtprotoUsage is what a secret has used and is using right now. +type mtprotoUsage struct { + active atomic.Int64 + bytesUp atomic.Int64 + bytesDown atomic.Int64 +} + +// mtprotoSnapshot is one secret's standing, for the API and the dashboard. +type mtprotoSnapshot struct { + Secret string `json:"secret"` + Active int64 `json:"active_connections"` + BytesUp int64 `json:"bytes_up"` + BytesDown int64 `json:"bytes_down"` +} + +// mtprotoUsageFor returns the counters for a secret, creating them on first use. +func (m *mtprotoServer) usageFor(secret string) *mtprotoUsage { + m.usageMu.Lock() + defer m.usageMu.Unlock() + if m.usage == nil { + m.usage = map[string]*mtprotoUsage{} + } + u, ok := m.usage[secret] + if !ok { + u = &mtprotoUsage{} + m.usage[secret] = u + } + return u +} + +// mtprotoUsageSnapshot reports every secret that has been used, so a dashboard +// polling once a second does not allocate. +func (m *mtprotoServer) mtprotoUsageSnapshot() []mtprotoSnapshot { + m.usageMu.Lock() + defer m.usageMu.Unlock() + out := make([]mtprotoSnapshot, 0, len(m.usage)) + for secret, u := range m.usage { + out = append(out, mtprotoSnapshot{ + Secret: secret, + Active: u.active.Load(), + BytesUp: u.bytesUp.Load(), + BytesDown: u.bytesDown.Load(), + }) + } + return out +} + // mtprotoServer accepts Telegram clients and relays them to a datacenter. type mtprotoServer struct { cfg Config // secrets is a getter, not a map: the set is replaced when the dashboard // changes it, and a copy taken at startup would keep serving secrets that // have since been revoked. - secrets func() mtprotoSecrets + secrets func() mtprotoGrants overrides map[int]string + // usage tracks, per secret, what a plan is measured against. + usageMu sync.Mutex + usage map[string]*mtprotoUsage + // cloakHost is the domain the fake TLS reply is built around when a client // does not name one of its own. cloakHost string @@ -401,12 +468,33 @@ func (m *mtprotoServer) handle(conn net.Conn) { dialTimeout = 10 * time.Second } - session, dc, err := m.accept(conn) + session, dc, grant, err := m.accept(conn) if err != nil { log.Debug("mtproto handshake refused", "error", err) return } + // The plan is enforced here rather than left to the SOCKS5 pipeline, which + // this relay does not pass through: without it every phone gets the same + // unlimited pipe regardless of what it is on the books for. + usage := m.usageFor(grant.name) + if over, limit := mtprotoOverDataCap(usage, grant.tier); over { + log.Warn("refused: data cap reached", "tier", grant.tier.Name, "limit", limit) + return + } + if max := grant.tier.MaxConnections; max > 0 && usage.active.Load() >= int64(max) { + log.Warn("refused: too many sessions", "tier", grant.tier.Name, "active", usage.active.Load(), "limit", max) + return + } + usage.active.Add(1) + defer usage.active.Add(-1) + + var upPacer, downPacer *pacer + if mbps := grant.tier.BandwidthMbps; mbps > 0 { + upPacer = newPacer(mbps) + downPacer = newPacer(mbps) + } + upstream, err := mtprotoDial(dc, dialTimeout, m.overrides) if err != nil { log.Warn("cannot reach the datacenter", "dc", dc, "error", err) @@ -425,14 +513,15 @@ func (m *mtprotoServer) handle(conn net.Conn) { // first side to go takes the other with it. go func() { defer closeBoth() - copyStream(upstream, session, log) + copyStreamCounted(upstream, session, log, upPacer, &usage.bytesUp) }() go func() { defer closeBoth() - copyStream(session, upstream, log) + copyStreamCounted(session, upstream, log, downPacer, &usage.bytesDown) }() - log.Info("mtproto session relayed", "dc", dc, "address", mtprotoDCAddress(dc, m.overrides)) + log.Info("mtproto session relayed", "dc", dc, "address", mtprotoDCAddress(dc, m.overrides), + "tier", grant.tier.Name) <-time.After(idle) closeBoth() } @@ -440,12 +529,12 @@ func (m *mtprotoServer) handle(conn net.Conn) { // accept reads the client's opening and works out which transport it speaks. // A TLS handshake starts 0x16; anything else is obfuscated2. The choice comes // from the first byte, which is what lets one port serve both. -func (m *mtprotoServer) accept(conn net.Conn) (*mtprotoSession, int, error) { +func (m *mtprotoServer) accept(conn net.Conn) (*mtprotoSession, int, mtprotoGrant, error) { secrets := m.secrets() peek := make([]byte, 1) if _, err := io.ReadFull(conn, peek); err != nil { - return nil, 0, err + return nil, 0, mtprotoGrant{}, err } // The peeked byte is the first byte of whichever handshake follows, so it is @@ -457,11 +546,14 @@ func (m *mtprotoServer) accept(conn net.Conn) (*mtprotoSession, int, error) { // anything else is read. wrapped, hello, err := fakeTLSHandshake(conn, secrets, time.Now(), m.cloakHost) if err != nil { - return nil, 0, err + return nil, 0, mtprotoGrant{}, err } m.log.Info("fake tls hello accepted", "domain", hello.Domain) session, dc, err := m.acceptWithSecret(wrapped, hello.Secret) - return session, dc, err + if err != nil { + return nil, 0, mtprotoGrant{}, err + } + return session, dc, m.grantForSecret(secrets, hello.Secret), nil } return m.acceptWithAnySecret(conn, secrets) @@ -490,18 +582,18 @@ func (m *mtprotoServer) acceptWithSecret(conn mtprotoConn, secret []byte) (*mtpr // from the same connection, so a wrong secret only costs the client opening // bytes: the server has consumed exactly the same 64 bytes either way, and the // stream is discarded between attempts. -func (m *mtprotoServer) acceptWithAnySecret(conn mtprotoConn, secrets mtprotoSecrets) (*mtprotoSession, int, error) { +func (m *mtprotoServer) acceptWithAnySecret(conn mtprotoConn, secrets mtprotoGrants) (*mtprotoSession, int, mtprotoGrant, error) { if len(secrets) == 0 { - return nil, 0, errors.New("no MTProto secret is configured") + return nil, 0, mtprotoGrant{}, errors.New("no MTProto secret is configured") } init := make([]byte, mtprotoInitLen) if _, err := io.ReadFull(conn, init); err != nil { - return nil, 0, err + return nil, 0, mtprotoGrant{}, err } var lastErr error - for _, secret := range secrets { - toPeer, fromPeer, err := mtprotoStreams(init, secret) + for _, grant := range secrets { + toPeer, fromPeer, err := mtprotoStreams(init, grant.key) if err != nil { lastErr = err continue @@ -522,21 +614,62 @@ func (m *mtprotoServer) acceptWithAnySecret(conn mtprotoConn, secrets mtprotoSec continue } dc := int(binary.LittleEndian.Uint16(probe[60:62])) - return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, dc, nil + return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, dc, grant, nil } if lastErr == nil { lastErr = errors.New("no configured secret matched") } - return nil, 0, lastErr + return nil, 0, mtprotoGrant{}, lastErr +} + +// grantForSecret finds the plan a fake TLS client belongs to. The hello proved +// which key it holds, so this is a lookup rather than another guess. +func (m *mtprotoServer) grantForSecret(secrets mtprotoGrants, key []byte) mtprotoGrant { + for _, grant := range secrets { + if hmac.Equal(grant.key, key) { + return grant + } + } + return mtprotoGrant{} } // copyStream moves bytes until one side stops or the idle window closes. func copyStream(dst io.Writer, src io.Reader, log *slog.Logger) { - // io.Copy rather than a hand-rolled loop: it deals with short writes, which - // a relay that drops them turns into silent truncation. - if _, err := io.CopyBuffer(dst, src, make([]byte, 32*1024)); err != nil { - log.Debug("mtproto relay ended", "error", err) + copyStreamCounted(dst, src, log, nil, nil) +} + +// copyStreamCounted is copyStream with the plan applied: the pacer holds the +// tier's bandwidth, and every byte is added to what the secret has used. +// +// io.CopyBuffer rather than a hand-rolled loop, because it deals with short +// writes -- and a relay that drops them truncates messages silently. The reader +// side counts bytes as it arrives, which is what the plan is billed on. +func copyStreamCounted(dst io.Writer, src io.Reader, log *slog.Logger, p *pacer, counter *atomic.Int64) { + buf := make([]byte, 32*1024) + for { + n, err := src.Read(buf) + if n > 0 { + if counter != nil { + counter.Add(int64(n)) + } + p.reserve(n) + if _, werr := dst.Write(buf[:n]); werr != nil { + return + } + } + if err != nil { + return + } + } +} + +// mtprotoOverDataCap reports whether a secret has used its allowance. +func mtprotoOverDataCap(usage *mtprotoUsage, tier Tier) (bool, int64) { + if tier.DataLimitBytes <= 0 { + return false, 0 } + used := usage.bytesUp.Load() + usage.bytesDown.Load() + return used >= tier.DataLimitBytes, tier.DataLimitBytes } // ─── Secrets ──────────────────────────────────────────────────────────────── @@ -601,8 +734,8 @@ func parseMTProtoSecret(stored string) ([]byte, error) { // database, so a fresh install gets one generated and can start serving // immediately rather than refusing to start and waiting to be configured. func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { - secrets = s.loadMTProtoSecrets(secrets, true) - if len(secrets) == 0 { + grants := s.loadMTProtoSecrets(secrets, true) + if len(grants) == 0 { return errors.New("no MTProto secret is configured; add one in the dashboard") } @@ -611,11 +744,6 @@ func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { return fmt.Errorf("listen on %s: %w", s.cfg.MTProtoBind, err) } - s.mtprotoMu.Lock() - s.mtprotoSecrets = secrets - s.mtprotoListener = listener - s.mtprotoMu.Unlock() - server := &mtprotoServer{ cfg: s.cfg, secrets: s.mtprotoLiveSecrets, @@ -625,10 +753,17 @@ func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { track: s.trackConn, untrack: s.untrackConn, listener: listener, + usage: map[string]*mtprotoUsage{}, } + s.mtprotoMu.Lock() + s.mtprotoSecrets = grants + s.mtprotoListener = listener + s.mtprotoServer = server + s.mtprotoMu.Unlock() + go server.serve() - s.logger.Info("MTProto enabled", "bind", s.cfg.MTProtoBind, "secrets", len(secrets), + s.logger.Info("MTProto enabled", "bind", s.cfg.MTProtoBind, "secrets", len(grants), "edit", "in the dashboard, or Telegram: Settings -> Data and Storage -> Proxy") return nil } @@ -639,8 +774,8 @@ func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { // be false: revoking the last secret has to leave the proxy refusing everyone, // because quietly minting a replacement would undo the operator's decision and // hand out a working credential they never asked for. -func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpty bool) mtprotoSecrets { - out := mtprotoSecrets{} +func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpty bool) mtprotoGrants { + out := mtprotoGrants{} if s.store != nil { if stored, err := s.store.ListMtprotoSecrets(); err != nil { s.logger.Warn("could not read MTProto secrets", "error", err) @@ -650,22 +785,29 @@ func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpt continue } if key, err := parseMTProtoSecret(sec.Secret); err == nil { - out[sec.Secret] = key + tier := Tiers[sec.Tier] + if tier.Name == "" { + tier = Tiers[defaultMtprotoTier] + } + out[sec.Secret] = mtprotoGrant{name: sec.Secret, key: key, tier: tier} } } } } if len(out) == 0 { + // Nothing stored: fall back to whatever was configured, held to the + // default plan rather than being quietly throttled. + tier := Tiers[defaultMtprotoTier] for name, key := range fallback { - out[name] = key + out[name] = mtprotoGrant{name: name, key: key, tier: tier} } } if len(out) == 0 && generateIfEmpty && s.store != nil { secret, err := generateMTProtoSecret(s.cfg.MTProtoSecretKind) if err == nil { - if _, err := s.store.CreateMtprotoSecret(secret, "generated"); err == nil { + if _, err := s.store.CreateMtprotoSecret(secret, "generated", defaultMtprotoTier); err == nil { if key, kerr := parseMTProtoSecret(secret); kerr == nil { - out[secret] = key + out[secret] = mtprotoGrant{name: secret, key: key, tier: Tiers[defaultMtprotoTier]} } s.logger.Info("generated the first MTProto secret", "secret", secret) } @@ -676,14 +818,14 @@ func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpt // setMTProtoSecrets replaces the live set after a dashboard change. Nothing has // to be restarted: the set is consulted on every connection. -func (s *ProxyServer) setMTProtoSecrets(secrets mtprotoSecrets) { +func (s *ProxyServer) setMTProtoSecrets(secrets mtprotoGrants) { s.mtprotoMu.Lock() s.mtprotoSecrets = secrets s.mtprotoMu.Unlock() } // mtprotoLiveSecrets is the set currently being served. -func (s *ProxyServer) mtprotoLiveSecrets() mtprotoSecrets { +func (s *ProxyServer) mtprotoLiveSecrets() mtprotoGrants { s.mtprotoMu.RLock() defer s.mtprotoMu.RUnlock() return s.mtprotoSecrets diff --git a/mtproto_test.go b/mtproto_test.go index a1317bb..9889578 100644 --- a/mtproto_test.go +++ b/mtproto_test.go @@ -292,7 +292,7 @@ func TestMTProtoRelayEndToEnd(t *testing.T) { s := NewProxyServer(cfg) s.store = newTestStore(t) - if _, err := s.store.CreateMtprotoSecret(secret, "test phone"); err != nil { + if _, err := s.store.CreateMtprotoSecret(secret, "test phone", "unlimited"); err != nil { t.Fatalf("store secret: %v", err) } if err := s.startMTProto(nil); err != nil { @@ -398,7 +398,7 @@ func TestMTProtoUnknownSecretRefused(t *testing.T) { s := NewProxyServer(cfg) s.store = newTestStore(t) - if _, err := s.store.CreateMtprotoSecret(secret, "the only one"); err != nil { + if _, err := s.store.CreateMtprotoSecret(secret, "the only one", "unlimited"); err != nil { t.Fatalf("store secret: %v", err) } if err := s.startMTProto(nil); err != nil { @@ -477,7 +477,7 @@ func TestMTProtoRevokingLastSecretDoesNotMintOne(t *testing.T) { s := NewProxyServer(cfg) s.store = newTestStore(t) - row, err := s.store.CreateMtprotoSecret(secret, "the only phone") + row, err := s.store.CreateMtprotoSecret(secret, "the only phone", "unlimited") if err != nil { t.Fatalf("store: %v", err) } @@ -526,3 +526,102 @@ func TestMTProtoRevokingLastSecretDoesNotMintOne(t *testing.T) { t.Errorf("the refusal took %v, so the connection was being relayed rather than refused", waited) } } + +// A plan that is only written down and never enforced is worse than no plan, so +// the limits are checked against real sessions. +func TestMTProtoTierLimitsAreEnforced(t *testing.T) { + // A tier whose caps are small enough to reach in a test. + tier := Tier{Name: "free", MaxConnections: 1, BandwidthMbps: -1, DataLimitBytes: 2048} + + usage := &mtprotoUsage{} + usage.bytesUp.Store(2048) + + if over, limit := mtprotoOverDataCap(usage, tier); !over || limit != 2048 { + t.Errorf("a secret at its data cap reported over=%v limit=%d, want true and 2048", over, limit) + } + usage.bytesDown.Store(1) + if over, _ := mtprotoOverDataCap(usage, tier); !over { + t.Error("usage below the cap was reported as over it") + } + + // An unlimited plan is never over, however much is used. + unlimited := Tiers["unlimited"] + usage.bytesUp.Store(1 << 40) + if over, _ := mtprotoOverDataCap(usage, unlimited); over { + t.Error("an unlimited tier reported a data cap") + } +} + +// The tiers the dashboard offers have to be the same ones the SOCKS5 port uses, +// or the two would drift into meaning different things. +func TestMTProtoSecretDefaultsToUnlimited(t *testing.T) { + store := newTestStore(t) + + secret, err := generateMTProtoSecret("dd") + if err != nil { + t.Fatalf("generate: %v", err) + } + // No tier given: Telegram access stays reachable instead of being throttled + // to 1Mbps by accident. + created, err := store.CreateMtprotoSecret(secret, "phone", "") + if err != nil { + t.Fatalf("create: %v", err) + } + if created.Tier != defaultMtprotoTier { + t.Errorf("tier = %q, want %q", created.Tier, defaultMtprotoTier) + } + + // A tier nobody invented is refused rather than silently stored. + if _, err := store.CreateMtprotoSecret(secret+"ff", "other", "platinum"); err == nil { + t.Error("an unknown tier was accepted") + } + + for name := range Tiers { + got, err := store.CreateMtprotoSecret(generateTestSecret(t), name, name) + if err != nil { + t.Fatalf("tier %q: %v", name, err) + } + if got.Tier != name { + t.Errorf("tier %q stored as %q", name, got.Tier) + } + } +} + +// An install that already has secrets must gain the column without losing them. +func TestMTProtoTierColumnMigration(t *testing.T) { + store := newTestStore(t) + + secret, err := generateMTProtoSecret("dd") + if err != nil { + t.Fatalf("generate: %v", err) + } + store.mu.Lock() + _, err = store.db.Exec( + "INSERT INTO mtproto_secrets (secret, label) VALUES (?, ?)", secret, "pre-migration") + store.mu.Unlock() + if err != nil { + t.Fatalf("seed an older row: %v", err) + } + + // Re-running the migration is what happens on every start. + if err := store.migrate(); err != nil { + t.Fatalf("migrate again: %v", err) + } + + secrets, err := store.ListMtprotoSecrets() + if err != nil || len(secrets) != 1 { + t.Fatalf("secrets = %+v, %v", secrets, err) + } + if secrets[0].Tier != defaultMtprotoTier { + t.Errorf("an existing secret came back as tier %q, want %q", secrets[0].Tier, defaultMtprotoTier) + } +} + +func generateTestSecret(t *testing.T) string { + t.Helper() + secret, err := generateMTProtoSecret("dd") + if err != nil { + t.Fatalf("generate: %v", err) + } + return secret +} diff --git a/web/index.html b/web/index.html index a132f0a..f2ac506 100644 --- a/web/index.html +++ b/web/index.html @@ -283,6 +283,15 @@

Telegram (MTProto)

+
+ + +
@@ -294,12 +303,14 @@

Telegram (MTProto)

ID Label Secret + Tier + Used Status Actions - Loading... + Loading... @@ -339,7 +350,7 @@

REALITY Clients (VLESS UUIDs)

- Loading... + Loading... @@ -641,7 +652,7 @@

Settings

tbody.innerHTML=''; if(!data.secrets||data.secrets.length===0){ var empty=el('tr'),ecell=el('td','No secrets yet. Add one above.'); - ecell.colSpan=5;ecell.style.color='#555'; + ecell.colSpan=6;ecell.style.color='#555'; empty.appendChild(ecell);tbody.appendChild(empty); return; } @@ -659,6 +670,9 @@

Settings

copy.onclick=function(){navigator.clipboard.writeText(c.secret)}; secretCell.appendChild(copy); row.appendChild(secretCell); + row.appendChild(el('td',c.tier||'unlimited')); + var used=data.usage&&data.usage[c.secret]; + row.appendChild(el('td',used?(used.active_connections+' live, '+formatBytes(used.bytes_up+used.bytes_down)+' sent'):'—')); var status=el('td'); var badge=el('span',c.enabled?'active':'disabled'); badge.className='badge '+(c.enabled?'badge-active':'badge-disabled'); @@ -669,10 +683,19 @@

Settings

var toggle=el('button',c.enabled?'Disable':'Enable'); toggle.className='btn btn-sm '+(c.enabled?'btn-danger':'btn-success'); toggle.onclick=function(){toggleMtprotoSecret(c.id,!c.enabled)}; + var plan=el('select'); + ['free','basic','pro','unlimited'].forEach(function(name){ + var opt=el('option',name);opt.value=name; + if((c.tier||'unlimited')===name)opt.selected=true; + plan.appendChild(opt); + }); + plan.className='btn btn-sm'; + plan.style.marginRight='5px'; + plan.onchange=function(){setMtprotoTier(c.id,this.value)}; var del=el('button','Del'); del.className='btn btn-sm btn-danger'; del.onclick=function(){deleteMtprotoSecret(c.id,c.label||c.secret)}; - actions.appendChild(toggle);actions.appendChild(del); + actions.appendChild(plan);actions.appendChild(toggle);actions.appendChild(del); row.appendChild(actions); tbody.appendChild(row); } @@ -684,7 +707,7 @@

Settings

async function createMtprotoSecret(){ var msg=document.getElementById('mtproto-msg'); - var body={label:document.getElementById('m-label').value,kind:document.getElementById('m-kind').value}; + var body={label:document.getElementById('m-label').value,kind:document.getElementById('m-kind').value,tier:document.getElementById('m-tier').value}; try{ var r=await fetch('/api/mtproto-secrets',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); if(r.ok){ @@ -708,6 +731,14 @@

Settings

loadMtprotoSecrets(); } +async function setMtprotoTier(id,tier){ + var msg=document.getElementById('mtproto-msg'); + var r=await fetch('/api/mtproto-secrets/'+id,{method:'PUT',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({tier:tier})}); + if(!r.ok){msg.textContent='Error: '+(await r.text());msg.className='msg msg-err';msg.style.display='block'} + else{msg.textContent='Plan updated.';msg.className='msg msg-ok';msg.style.display='block'} + loadMtprotoSecrets(); +} + async function deleteMtprotoSecret(id,label){ if(!confirm('Delete "'+label+'"? That phone stops working immediately.'))return; var msg=document.getElementById('mtproto-msg');