Documentation
¶
Overview ¶
Package state is xtune's data model and its storage on the server: the deployment and user database in state.json (State, Entry, User and the settings they hold) and the traffic counters in usage.json (Usage). It holds the types, how they are read and written, and simple accessors; building configs from them and changing them lives with the features that do it.
Index ¶
- Constants
- Variables
- func DayKey(t time.Time) string
- func EntryKey(e Entry) string
- func HasEngine(es []Entry, engine string) bool
- func NewSSKey() string
- func NewUUID() string
- func Save(r *remote.Server, st *State) error
- func SaveUsage(r *remote.Server, us *Usage) error
- func UserStatus(u User, uu *UserUsage, now time.Time) string
- type AWGParams
- type Autopilot
- type BackupPlan
- type Cloudflare
- type Entry
- func (e Entry) CDN() bool
- func (e Entry) Engine() string
- func (e Entry) Family() string
- func (e Entry) HandshakeOnly() bool
- func (e Entry) Knobs() Knobs
- func (e Entry) Net() string
- func (e Entry) Proto() string
- func (e Entry) Reality() bool
- func (e Entry) SSH() bool
- func (e Entry) Trojan() bool
- func (e Entry) VlessEnc() bool
- func (e Entry) Worker() bool
- func (e Entry) Xray() bool
- type EntryUsage
- type Follow
- type Forward
- type IPBlock
- type J
- type Knobs
- type Manage
- type Naming
- type NetRank
- type NewerError
- type Notify
- type PeerHub
- type PeerServer
- type Plan
- type PublicPool
- type Relay
- type RelaySSH
- type Reseller
- type S3Target
- type State
- type SubConfig
- type Usage
- type User
- type UserUsage
- type Warp
- type Worker
- type WorkerExtra
- type WorkerUse
Constants ¶
const ( DefaultConfigName = "{flag} {user}-{id}" DefaultSubName = "{flag} xtune - {user}" )
Placeholders in the templates: {flag} {country} {server} {user} {id} {proto} {port}, and {via} for the relay a config goes through. Parts left empty are dropped with their separators.
const HistoryDays = 60
HistoryDays is how many days of per-user traffic are kept.
const Schema = 1
Schema is the format of state.json and usage.json this xtune reads and writes. Files from every 0.x release have no "schema" field, which reads as 0.
When a release changes the meaning or name of a field, it raises Schema and adds a migration; fields that are only added need neither (older files just lack them). A file with a newer schema is refused rather than rewritten: an older xtune would drop what it does not know.
Variables ¶
var Kinds = map[string]struct { Engine string // xray | tunnel | awg | openvpn | ikev2 Handshake bool // tuning can only measure the handshake }{ "reality-tcp": {Engine: "xray"}, "reality-xhttp": {Engine: "xray"}, "reality-grpc": {Engine: "xray"}, "vlessenc-tcp": {Engine: "xray"}, "vlessenc-xhttp": {Engine: "xray"}, "cdn-xhttp": {Engine: "xray"}, "hysteria2": {Engine: "xray"}, "ss2022": {Engine: "xray"}, "wireguard": {Engine: "xray"}, "worker-ws": {Engine: "xray"}, "trojan-reality": {Engine: "xray"}, "amneziawg": {Engine: "awg"}, "ssh": {Engine: "tunnel"}, "ssh-tls": {Engine: "tunnel"}, "cdn-ssh": {Engine: "tunnel"}, "dnstt": {Engine: "tunnel"}, "mtproto": {Engine: "tunnel", Handshake: true}, "openvpn-udp": {Engine: "openvpn", Handshake: true}, "openvpn-tcp": {Engine: "openvpn", Handshake: true}, "ikev2": {Engine: "ikev2", Handshake: true}, }
Kinds describes each kind: what serves it and how it is measured.
var WgSubnet = netip.MustParsePrefix("10.66.0.0/16")
WgSubnet holds the users' tunnel addresses; the server never needs one of its own.
Functions ¶
func EntryKey ¶
EntryKey identifies a deployed config: a redeploy that moves it to another port starts over.
Types ¶
type AWGParams ¶
type AWGParams struct {
Jc int `json:"jc"`
Jmin int `json:"jmin"`
Jmax int `json:"jmax"`
S1 int `json:"s1"`
S2 int `json:"s2"`
H1 uint32 `json:"h1"`
H2 uint32 `json:"h2"`
H3 uint32 `json:"h3"`
H4 uint32 `json:"h4"`
Priv string `json:"privateKey"` // server key (base64)
Public string `json:"publicKey"`
}
AWGParams are the obfuscation settings server and clients share.
type Autopilot ¶
type Autopilot struct {
Provider string `json:"provider"` // digitalocean
Token string `json:"token"` // API token (write access to reserved IPs)
Droplet int64 `json:"droplet,omitempty"` // this server's droplet ID
Owned string `json:"owned,omitempty"` // the reserved IP xtune assigned, released at the next move
}
Autopilot is the provider the server can get a new IP from.
type BackupPlan ¶
type BackupPlan struct {
Every int64 `json:"every"` // seconds between backups
Pass string `json:"pass"` // passphrase the backups are sealed with
Telegram bool `json:"telegram,omitempty"` // send to the alert chat (xtune notify telegram)
S3 *S3Target `json:"s3,omitempty"`
}
BackupPlan is the schedule and where the backups go.
type Cloudflare ¶
type Cloudflare struct {
Token string `json:"token,omitempty"`
}
type Entry ¶
type Entry struct {
ID string `json:"id"`
Kind string `json:"kind"` // see kinds
Port int `json:"port"`
SNI string `json:"sni,omitempty"`
Path string `json:"path,omitempty"`
Svc string `json:"svc,omitempty"`
Primary bool `json:"primary,omitempty"`
FP string `json:"fp,omitempty"`
Mode string `json:"mode,omitempty"`
Frag string `json:"frag,omitempty"`
Split string `json:"split,omitempty"` // cdn-xhttp: "cdn-up" uploads through the CDN and downloads straight from the server
Hop string `json:"hop,omitempty"` // hysteria2: UDP port range forwarded to Port, for port hopping ("20000-20999")
MTU int `json:"mtu,omitempty"` // wireguard: tunnel MTU
Resolver string `json:"resolver,omitempty"` // dnstt: the resolver clients send queries through
Subnet string `json:"subnet,omitempty"` // amneziawg: the clients' address range
Addr string `json:"addr,omitempty"` // CDN and Worker entries: a Cloudflare edge IP to dial (a clean IP)
ALPN string `json:"alpn,omitempty"` // cdn-xhttp: "h3" reaches the CDN over HTTP/3 (QUIC)
}
Entry is one server inbound. FP/Mode/Frag are the client-side knobs tuning picked for it.
func (Entry) CDN ¶
CDN entries are reached through the CDN domain: TLS ends at the CDN, which forwards to the origin.
func (Entry) Family ¶
Family groups kinds into the opt-in protocols of --protocols ("" for the default matrix).
func (Entry) HandshakeOnly ¶
HandshakeOnly entries are VPNs: tuning sees whether the handshake answers, not throughput.
type EntryUsage ¶
type EntryUsage struct {
Bytes int64 `json:"bytes"`
First int64 `json:"first"` // when it was first seen deployed
Active int64 `json:"active,omitempty"` // last run it carried traffic
}
EntryUsage is the traffic of one deployed config. A config that stops carrying anything while the others still do is probably blocked on the users' networks.
type Forward ¶
type Forward struct {
ID string `json:"id"` // the entry it carries
Port int `json:"port"` // listening on the relay
To int `json:"to"` // the entry's port on this server
Net string `json:"net"` // tcp | udp
Ms int `json:"ms,omitempty"` // relay → server TCP connect time when last synced, 0 = not measured (UDP)
}
Forward is one port the relay forwards: Port on the relay to To on this server.
type Knobs ¶
Knobs are client-side settings. Split applies to cdn-xhttp only, MTU to wireguard, Resolver to dnstt; Mode is the XHTTP mode, or for SSH entries "ws" when the client opens with a WebSocket upgrade request. Addr is the Cloudflare edge IP CDN and Worker entries dial instead of resolving their domain; ALPN "h3" has the CDN entry reach the CDN over HTTP/3.
type Naming ¶
type Naming struct {
Label string `json:"label,omitempty"` // this server's name, {server} in the templates ("Frankfurt")
// Flag is the ISO 3166-1 alpha-2 code of the country traffic leaves from: the server's own
// location. "" = not known yet (looked up automatically), "off" = no flag.
Flag string `json:"flag,omitempty"`
Detected bool `json:"detected,omitempty"` // Flag came from a lookup, so a move to a new IP looks it up again
Checked int64 `json:"checked,omitempty"` // unix seconds of the last failed lookup, to retry daily
Config string `json:"config,omitempty"` // config name template, "" = DefaultConfigName
Sub string `json:"sub,omitempty"` // subscription name template, "" = DefaultSubName
Via string `json:"-"` // the relay these configs go through: {via}, set on the relay's view only
}
Naming is how client apps show this server's configs and subscriptions. Every field is optional: the zero value names configs "USER-ID" and subscriptions "xtune - USER", with the flag of the server's country in front once it is known.
type NetRank ¶
type NetRank struct {
Name string `json:"name,omitempty"` // the ISP, as the ASN registry names it
Updated int64 `json:"updated"`
Scores map[string]float64 `json:"scores"` // by EntryKey; 0 = blocked there
Addrs map[string]string `json:"addrs,omitempty"` // by EntryKey: CDN and Worker configs' clean IP there
}
NetRank is how the deployed configs did from one network.
type NewerError ¶
NewerError is a file written by a newer xtune.
func (*NewerError) Error ¶
func (e *NewerError) Error() string
type Notify ¶
type Notify struct {
TelegramToken string `json:"telegramToken,omitempty"`
TelegramChat string `json:"telegramChat,omitempty"`
Webhook string `json:"webhook,omitempty"` // receives {"text","content","event","server"} as JSON
}
Notify sends admin alerts (quota, expiry, Xray down) to Telegram and/or a webhook. The enforce job checks for them every minute and sends each alert once, until its condition clears.
type PeerHub ¶
type PeerHub struct {
Secret string `json:"secret"`
Servers map[string]*PeerServer `json:"servers,omitempty"`
}
PeerHub is the primary's side: the secret followers use, and what they last reported.
type PeerServer ¶
type Plan ¶
type PublicPool ¶
type PublicPool struct {
Token string `json:"token"` // secret part of the connect link
QuotaGB float64 `json:"quotaGB,omitempty"` // per member
Days int `json:"days,omitempty"`
Devices int `json:"devices,omitempty"`
Reset string `json:"reset,omitempty"`
Plan string `json:"plan,omitempty"` // limits come from this plan instead, when set
Members int `json:"members,omitempty"` // most active members at once, 0 = unlimited
Paused bool `json:"paused,omitempty"` // no new members; existing ones keep working
Created int64 `json:"created"`
}
func (PublicPool) String ¶
func (p PublicPool) String() string
type Relay ¶
type Relay struct {
Name string `json:"name"`
Addr string `json:"addr"` // the address clients dial: the relay's IP or a domain pointing at it
SSH RelaySSH `json:"ssh"` // how xtune reaches the relay again (sync, removal); never a secret
Target string `json:"target"` // the address of this server the relay forwards to
Forwards []Forward `json:"forwards"`
Added int64 `json:"added"`
}
Relay is a server, usually in the users' own country, that forwards ports to this one: client → relay → this server (multi-hop). Domestic routes are often filtered less than international ones, and datacenter-to-datacenter links less than home and mobile ones. The relay holds no keys and no users: configs through it are this server's configs, dialled at the relay's address.
type RelaySSH ¶
type RelaySSH struct {
Host string `json:"host"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
}
RelaySSH is the relay's SSH address. Passwords and keys stay on the admin's computer.
type Reseller ¶
type Reseller struct {
Token string `json:"token"`
MaxUsers int `json:"maxUsers,omitempty"`
QuotaGB float64 `json:"quotaGB,omitempty"` // total quota of their users; each then needs a quota
}
A Reseller manages their own users only, within limits. 0 = no limit.
type S3Target ¶
type S3Target struct {
Endpoint string `json:"endpoint"` // https://ACCOUNT.r2.cloudflarestorage.com
Region string `json:"region"` // "auto" for R2
Bucket string `json:"bucket"`
Prefix string `json:"prefix,omitempty"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
}
S3Target is a bucket on an S3-compatible service, addressed path-style.
type State ¶
type State struct {
Schema int `json:"schema"` // the file's format, see Schema
Host string `json:"host"`
Domain string `json:"domain,omitempty"` // direct (DNS-only) domain used instead of Host in links
CDNDomain string `json:"cdnDomain,omitempty"` // CDN-proxied domain for the cdn-* entries
RealityPriv string `json:"realityPrivateKey"`
RealityPub string `json:"realityPublicKey"`
ShortID string `json:"shortId"`
VencDec string `json:"vlessDecryption"`
VencEnc string `json:"vlessEncryption"`
SSKey string `json:"ssServerKey"`
CertSNI string `json:"certSni"`
CertHash string `json:"certSha256"`
CertPEM string `json:"certPem"`
KeyPEM string `json:"keyPem"`
Entries []Entry `json:"entries"`
Users []User `json:"users"`
APIPort int `json:"apiPort,omitempty"` // Xray API on 127.0.0.1, for live user changes and stats
Country string `json:"country,omitempty"` // client configs send this country's sites direct
Sub SubConfig `json:"sub"`
Check *User `json:"check,omitempty"` // hidden user `xtune check` measures the deployed configs with
Warp *Warp `json:"warp,omitempty"` // Cloudflare WARP outbound for chosen sites
Notify Notify `json:"notify,omitzero"` // admin alerts
LegacyBot json.RawMessage `json:"bot,omitempty"` // the Telegram bot removed in v0.7.0: Enforce removes its unit, then this
Manage *Manage `json:"manage,omitempty"` // management links, used by the community VPN bot
Plans map[string]Plan `json:"plans,omitempty"` // named sets of limits for adding and renewing users
Cloudflare Cloudflare `json:"cloudflare,omitzero"` // API token for DNS records and the SSL mode
Peers *PeerHub `json:"peers,omitempty"` // primary: followers whose configs join the subscriptions
Follow *Follow `json:"follow,omitempty"` // follower: the users come from a primary
Public map[string]*PublicPool `json:"public,omitempty"` // public profiles: pools of users shared through a bot
AWG *AWGParams `json:"awg,omitempty"` // AmneziaWG key and obfuscation settings
Worker *Worker `json:"worker,omitempty"` // Cloudflare Worker relaying the worker-ws entries
Backups *BackupPlan `json:"backups,omitempty"` // scheduled backups sent off the server
Networks map[string]*NetRank `json:"networks,omitempty"` // configs ranked per network (ASN), for subscriptions
Autopilot *Autopilot `json:"autopilot,omitempty"` // where to get a new IP when this one is blocked
ClientIP string `json:"clientIp,omitempty"` // the address clients use instead of Host (a reserved IP)
Naming Naming `json:"naming,omitzero"` // config and subscription names, with the country flag
Relays []Relay `json:"relays,omitempty"` // servers that forward ports here: multi-hop
WGPriv string `json:"wgPrivateKey,omitempty"` // WireGuard server key (base64)
WGPub string `json:"wgPublicKey,omitempty"`
SSHHostKey string `json:"sshHostKey,omitempty"` // SSH tunnel host key (OpenSSH PEM)
SSHHostPub string `json:"sshHostPub,omitempty"` // authorized_keys format; clients pin it
DNSTTKey string `json:"dnsttKey,omitempty"` // DNS tunnel Noise key (hex)
DNSTTPub string `json:"dnsttPub,omitempty"`
DNSDomain string `json:"dnsDomain,omitempty"` // zone delegated to the server for the DNS tunnel
VPNCA string `json:"vpnCa,omitempty"` // CA for OpenVPN and IKEv2 (PEM); clients trust it
VPNCAKey string `json:"vpnCaKey,omitempty"`
VPNCert string `json:"vpnCert,omitempty"` // server certificate, for VPNName
VPNKey string `json:"vpnKey,omitempty"`
VPNName string `json:"vpnName,omitempty"` // the address the server certificate is for
}
State is the server's deployment and user database, stored as state.json (root, 0600).
func (*State) AssignWGIPs ¶
func (st *State) AssignWGIPs()
AssignWGIPs gives every user (and the check user) a tunnel address that stays theirs.
type SubConfig ¶
type SubConfig struct {
Mode string `json:"mode,omitempty"` // cdn (through the CDN domain) | direct (Let's Encrypt on the direct domain)
Port int `json:"port,omitempty"`
Path string `json:"path,omitempty"` // secret path prefix
Lang string `json:"lang,omitempty"` // page language: en | fa ("" = from the browser)
// Port443: the server also listens on 443, for the connect and management links: bots on
// serverless platforms (such as @chthvpnbot on tgcloud) can only reach ports 80 and 443.
Port443 bool `json:"port443,omitempty"`
Metrics string `json:"metrics,omitempty"` // token for /PATH/metrics (Prometheus), "" = off
}
SubConfig is the subscription server: off when Mode is empty.
type Usage ¶
type Usage struct {
Schema int `json:"schema,omitempty"` // the file's format, see Schema
Users map[string]*UserUsage `json:"users"`
Blocks []IPBlock `json:"blocks,omitempty"` // device-limit blocks
ActiveKey string `json:"activeKey,omitempty"` // which users config.json was last written for
Updated int64 `json:"updated,omitempty"`
Notified map[string]int64 `json:"notified,omitempty"` // alerts sent, so each is sent once
Failures int `json:"failures,omitempty"` // enforce runs in a row the Xray API failed
Entries map[string]*EntryUsage `json:"entries,omitempty"` // traffic per deployed config, by EntryKey
BackupAt int64 `json:"backupAt,omitempty"` // last scheduled backup attempt (before v0.7.0: the bot's)
SNIAt int64 `json:"sniAt,omitempty"` // last check of the REALITY targets
Synced map[string][2]int64 `json:"synced,omitempty"` // follower: traffic already reported to the primary
Extra map[string][2]int64 `json:"extra,omitempty"` // SSH tunnel and VPN counters at the last run
LastBackup int64 `json:"lastBackup,omitempty"` // last scheduled backup that was delivered
BackupErr string `json:"backupErr,omitempty"` // why the last attempt failed
WorkerAt int64 `json:"workerAt,omitempty"` // last check of the Workers' request counts
WorkerUse []WorkerUse `json:"workerUse,omitempty"` // requests per Worker today, at that check
Online map[string]int64 `json:"online,omitempty"` // primary: "user|ip" -> when first seen online on any server
RotatedAt int64 `json:"rotatedAt,omitempty"` // autopilot: last time it moved the server to a new IP
}
Usage is what the enforce job measures, stored in usage.json next to state.json. Traffic counters in Xray reset when it restarts, so totals are accumulated here every minute.
func DecodeUsage ¶
DecodeUsage reads usage.json, from any schema up to the current one.
type User ¶
type User struct {
Name string `json:"name"`
UUID string `json:"uuid"`
SSKey string `json:"ssKey"`
Enabled bool `json:"enabled"`
Created int64 `json:"created"`
Quota int64 `json:"quota,omitempty"` // traffic in bytes, 0 = unlimited
Expires int64 `json:"expires,omitempty"` // unix seconds, 0 = never
Devices int `json:"devices,omitempty"` // simultaneous client IPs, 0 = unlimited
SubToken string `json:"subToken,omitempty"` // secret part of the user's subscription URL
Reset string `json:"reset,omitempty"` // usage starts from zero every period: monthly | weekly
ResetAt int64 `json:"resetAt,omitempty"` // unix seconds of the next reset
Plan string `json:"plan,omitempty"` // plan the user was added or renewed with
Reseller string `json:"reseller,omitempty"` // reseller (management link) who manages this user
WGIP string `json:"wgIp,omitempty"` // WireGuard tunnel address
Pool string `json:"pool,omitempty"` // public profile the user is a member of
WGOnly bool `json:"-"` // a WireGuard test peer (wgVariantUser): its UUID is not a real UUID
}
type UserUsage ¶
type UserUsage struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
LastSeen int64 `json:"lastSeen,omitempty"`
Online []string `json:"online,omitempty"` // client IPs at the last check
Daily map[string]int64 `json:"daily,omitempty"` // bytes per day (server date), the last HistoryDays days
}
type Warp ¶
type Warp struct {
PrivateKey string `json:"privateKey"`
Address4 string `json:"address4"`
Address6 string `json:"address6,omitempty"`
PeerKey string `json:"peerPublicKey"`
Endpoint string `json:"endpoint"`
Reserved []int `json:"reserved,omitempty"` // client id, sent in every packet
Domains []string `json:"domains,omitempty"` // routing domains that use WARP
All bool `json:"all,omitempty"` // all traffic uses WARP
}
Warp sends chosen sites (or all traffic) out through Cloudflare WARP instead of the server's own IP: many services refuse datacenter IPs. The account is a free WARP registration.
type Worker ¶
type Worker struct {
Account string `json:"account"`
Name string `json:"name"`
Host string `json:"host"` // NAME.SUBDOMAIN.workers.dev
Domain string `json:"domain,omitempty"` // a hostname on one of the user's zones
Routes map[string]string `json:"routes,omitempty"` // path -> origin IP:port, as last uploaded
Extra []*WorkerExtra `json:"extra,omitempty"` // more Workers, in other accounts, on the same routes
Limit int64 `json:"limit,omitempty"` // requests a day for the usage alerts: 0 = the free plan's, -1 = no alerts
}
Worker is the deployment's Cloudflare Worker.
type WorkerExtra ¶
type WorkerExtra struct {
Token string `json:"token"` // that account's API token (Account: Workers Scripts:Edit, Account Analytics:Read)
Account string `json:"account"`
Name string `json:"name"`
Host string `json:"host"` // NAME.SUBDOMAIN.workers.dev
}
WorkerExtra is another Worker, in another account, relaying to the same inbounds.