mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-17 18:16:08 +00:00
5e1cb7693b
* fix(email): resolve a name-addr smtpFrom into bare envelope address and display name The save-time validator accepts any RFC 5322 address form, so a value like '3x-ui Panel <panel(at)example.com>' passes validation, but Send and TestConnection fed that raw string to MAIL FROM, which strict servers reject with 501, and buildMessage mangled it into a quoted local part. Parse the configured sender at the point of use: the envelope gets the bare address and, when no explicit sender name is set, the display name embedded in the setting is used for the From header. * fix(email): report a missing sender address from the SMTP connection test TestConnection skipped the empty-from guard that Send enforces, so with no sender and no username configured the test issued the null reverse-path and could report success against a lenient relay while every real notification send kept failing with the missing-sender error. Guard the test path the same way and surface a dedicated translated message. * fix(sub): fall back to the raw subscription when an auto-detected format has no content With format auto-detection enabled, a client whose User-Agent matched the Clash or JSON regex was routed straight to that format handler. For a subscription whose entries convert to neither format (an MTProto-only subscription, for example) the handler returns an empty document and the request ended as 404, breaking a URL that served the raw list before the toggle. The auto-detect branches now serve the detected format only when it produces content and otherwise continue to the raw response; the explicit format endpoints keep answering 404 for empty documents. * fix(node): match prefixed central tags when filtering a selected-mode node snapshot FilterNodeSnapshot compared a node snapshot's inbound tags against the raw selected-tag list with an exact match, while its two siblings (SnapshotHasUnadoptedInbounds and the reconcile tagToCentral map) expand each selected tag to both its bare node-side form and its n<id>- prefixed central form. A panel-created node inbound is recorded in the selected list under the central prefixed tag but reported by the node under the bare tag, so the exact match dropped it from every snapshot and the orphan sweep then deleted its central row one tick after creation. Expand the allowed set with the same prefix flip the siblings use. * fix(client): refuse a bulk quota reduction that would fall to or below zero BulkAdjust clamped a client's new traffic limit with max(total+addBytes, 0). Because 0 is the unlimited sentinel, reducing a client's quota by more than it had left silently granted that client unlimited traffic. The sibling expiry branch already refuses an over-reduction; mirror it for quota so the adjustment is skipped with a clear reason instead of crossing the sentinel. * fix(client): persist a bulk adjustment's applied field even when the sibling field is skipped In a mixed BulkAdjust (both a days delta and a bytes delta), a per-field planning skip such as "unlimited expiry" or "unlimited traffic" was recorded in the same map that gated the client_traffics write. The applied field was already written to the inbound JSON and the clients table, but the enforcement row was left untouched, so the depletion job cut the client on the old limit while the panel showed the new one. Gate the traffic-row write on an actual inbound-processing failure rather than on any planning-phase skip note. * fix(inbound): always create in AddInbound instead of overwriting a row whose id was posted The add controller binds the inbound model's id form field and never clears it, and AddInbound persisted with GORM Save, which updates in place when the primary key is non-zero. A client that reused an existing id (for instance by duplicating an inbound fetched from /get and changing the port) silently overwrote that stored row instead of creating a new inbound. Zero the id at the top of AddInbound, matching how it already zeroes the client-stat ids. * fix(inbound): accept WireGuard clients when creating an inbound AddInbound's per-client validation switch had cases for every protocol except WireGuard, so a WireGuard client fell through to the default branch that requires a non-empty id. WireGuard clients are keyed by their public key and carry no id, so importing a WireGuard inbound or re-adding one to a reconciling node was rejected with "empty client ID". Add a wireguard case that validates the client key, mirroring addInboundClient. * fix(client): stop holding the inbound-lock registry mutex while waiting on one inbound lockInbound acquired the global registry mutex and then blocked on the per-inbound mutex without releasing the registry first. A slow client operation holding one inbound's mutex (for example a bulk delete pushing to an unreachable node) made the next waiter park on that inbound while still holding the registry mutex, which in turn blocked lockInbound for every other inbound — freezing client mutations panel-wide. Release the registry mutex before taking the per-inbound lock. * fix(client): honor keepTraffic when deleting a client that is attached to inbounds Delete, DeleteByEmail and BulkDelete all pass keepTraffic to their final cleanup transaction, but each called the per-inbound delete helper with a hardcoded false. That helper purges the client's traffic, IP and stat rows before the gated cleanup runs, so keepTraffic=true still destroyed all traffic history for any client actually attached to an inbound (the pinned test only covered a record with no inbound mappings). Thread the caller's keepTraffic through to the per-inbound helper at all three call sites. * fix(inbound): defer a local MTProto inbound edit's sidecar push until after commit UpdateInbound applied a local MTProto inbound change by calling the runtime UpdateInbound (which stops/starts the mtg sidecar or talks to it) from inside runSerializedTx. That runs process and network I/O on the single traffic-writer goroutine while a DB transaction is open, so a slow sidecar stalls traffic accounting and every concurrent client mutation, and a later step failing the transaction leaves the sidecar ahead of the rolled-back row. Move the push into the post-commit hook, matching the xray branch. Adds a SetLocalRuntimeOverride test seam mirroring the existing node override so the deferral is regression tested. * fix(client): delete external-link rows when bulk-deleting clients The single-client Delete path removes a client's client_external_links rows, but BulkDelete (and the DelDepleted reaper that routes through it) deleted the record, mappings and traffic while leaving the external-link rows keyed by the now-dead client id, so they accumulated as orphans. Delete them in the same cleanup transaction, keyed by client id like the single path. * fix(inbound): request an xray restart when toggling a routed MTProto inbound AddInbound, DelInbound and UpdateInbound all flag needRestart when an inbound routes MTProto through xray, so the egress SOCKS bridge is regenerated. Only SetInboundEnable's local path omitted it, so toggling a routed MTProto inbound off then on left the bridge out of the running config while the sidecar dialed its loopback port, blackholing that inbound until an unrelated restart. Flag the restart on the local enable path too. * fix(client): apply enable-by-email to every inbound a client is attached to ToggleClientEnableByEmail (Telegram bot) and SetClientEnableByEmail (LDAP sync) resolved a single inbound via the legacy client_traffics pointer and flipped enable only there. A client attached to several inbounds kept connecting through the siblings' running Xray after being disabled, and the next edit could re-enable it everywhere from a stale sibling. Route both through the applyClientFieldByEmail fan-out (the #5039 fix path) so the whole multi-inbound identity is toggled at once, dropping the circular Set/Toggle dependency. * fix(traffic): commit a traffic tick even when a best-effort maintenance helper fails addTrafficLocked stages the inbound and client deltas, then runs three helpers (auto-renew, disable depleted clients, disable depleted inbounds) that are meant to log and continue. All three reused the function-scope err that the deferred commit/rollback inspects, so the last helper's error decided the whole tick: a failure in disableInvalidInbounds rolled back the already-staged traffic while AddTraffic reported success, and because xray had already advanced its counter baseline that traffic was lost for good. Give each best-effort helper its own error variable so only a genuine staging failure rolls the tick back. * fix(traffic): re-enable clients and serialize the write in Reset All Client Traffic ClientService.ResetAllTraffics zeroed up/down but, unlike every sibling reset path, never restored enable=true, so clients that had been auto-disabled for exceeding their quota stayed cut with zero usage after a reset. It also wrote client_traffics directly on the shared DB handle instead of through the serial traffic writer, reintroducing the cross-transaction lock-order deadlock the writer exists to prevent. Restore enable and run the reset inside submitTrafficWrite within one transaction. * fix(traffic): keep node reset propagation out of the serial traffic writer ResetAllTraffics and ResetInboundTraffic performed their remote-node reset HTTP calls inside submitTrafficWrite. Each call can block up to the remote timeout, and Reset All Traffics loops every node serially, so the single traffic-writer goroutine was held for seconds — long enough that the concurrent 5s traffic poll timed out submitting its own write and dropped the deltas it had already drained from xray. Do the DB reset inside the writer, then propagate to the nodes after it returns, matching how the mtproto quota reset is already sequenced. * fix(sub): stop the subscription from 500ing on valid-but-unusual stream settings The raw share-link generators used unchecked type assertions and unguarded array indexing: an empty Reality shortIds/serverNames array (random.Num(0) panics), a tcp-http header with no request block or an empty request.path, a grpc block missing its keys, empty stream settings, and a non-string Host header all panicked mid-generation. Because getSubs loops every client's link with no recover, one such client 500s the entire subscription for everyone. The sibling JSON, Clash and frontend generators already guard these; make the raw generators match with comma-ok assertions and length checks. * fix(sub): tolerate a hysteria inbound without hysteriaSettings in the JSON subscription genHy asserted stream["hysteriaSettings"].(map[string]any) without the comma-ok form, so a hysteria inbound whose StreamSettings omit the hysteriaSettings key (a valid, representable shape the raw generator renders fine) panicked and 500ed the entire JSON subscription. Use comma-ok; the downstream reads already guard each key, so a nil map degrades gracefully. * fix(sub): emit the pinned peer cert sha256 in Clash subscriptions The Clash stream builder computed tlsSettings["pin-sha256"] from the inbound's pinnedPeerCertSha256, but applySecurity's tls case never copied it onto the proxy, so it was written with no reader and silently dropped. Clash subscribers lost certificate pinning while JSON subscribers kept it. Surface pin-sha256 on the proxy in the tls case, matching the JSON emitter. * fix(link): parse the snake_case and extra-blob xhttp fields when importing a share link The panel's share-link emitters (Go and TS) carry advanced xhttp knobs as a snake_case x_padding_bytes plus an extra=<json> payload, but the Go parser's xhttp branch read only top-level camelCase params, so importing an xhttp link via the outbound-subscription feature dropped xPaddingBytes, scMaxEachPostBytes and the rest, silently reverting them to the stream defaults and producing a non-working outbound. Mirror the TS parser: read the snake_case alias, merge the extra JSON blob, then let explicit camelCase params win. * fix(frontend): decode URL-safe base64 when parsing an imported share link Base64.decode called window.atob directly, which rejects the base64url alphabet (- and _) and unpadded input. But the panel's own share-link emitter uses Base64.encode(x, true) (URL-safe, unpadded), and real SIP002 links do too, so importing a Shadowsocks link whose method:password encodes with a - or _ threw, fell back to the raw undecoded string, and produced a wrong method and garbage password (the vmess parser shared the same limitation). Normalize base64url and re-pad before atob so decode round-trips every emitted link. * fix(link): honor the vmess ws path and hysteria2 vcn params on import Two Go/TS parser parity gaps in the outbound share-link import path: parseVmess only applied a ws link's path when the inner JSON also carried a host key, so a generator that omits host dropped the path back to the default; and parseHysteria2 hardcoded verifyPeerCertByName to empty, ignoring the vcn param the panel emits, so a hysteria2 outbound with a decoy SNI and a distinct cert name failed TLS verification after import. The TS parser handles both; make the Go parser match. * fix(ui): stop the sniffing form island from clobbering unrendered fields antd's Form.useWatch only reports registered fields, so while the sniffing toggle was off the island emitted { enabled: false } upward and replaced the full Sniffing object in form state. Saving a VLESS reverse outbound then crashed in sniffingToWire on the missing ipsExcluded array; the loopback outbound and the inbound sniffing tab shared the same hole. Watch the store with preserve: true so unrendered fields keep their values, and seed a missing value from the schema defaults instead of an empty cast. * fix(sub): drop empty remark segments instead of leaving a stray separator expandSegment dropped a "|" segment only when its tokens rendered the unlimited mark, so a segment whose only token resolved to the empty string (a client with no comment, an unlimited client's expiry date) was kept as bare decoration, leaving a trailing "|" or a dangling emoji on every share link's remark. Drop a token-bearing segment whenever none of its tokens produce a real value, while still keeping pure-literal segments. * fix(xray): keep source- and domains-scoped routing rules when an inbound is deleted removeInboundTagFromRules drops a routing rule whose inboundTag list becomes empty only if the rule has no other matcher, but routingMatcherKeys omitted xray-core's canonical source and domains keys. A rule scoped by source or domains (common in hand-authored or imported configs) therefore lost its whole body — including a security-relevant block — when its single listed inbound was deleted, instead of just having the tag trimmed. Recognize source and domains as live matchers. * fix(xray): guard RemoveUser against an uninitialized handler client Every XrayAPI handler method returns an error when HandlerServiceClient is nil, except RemoveUser, which dereferenced it directly. A depletion sweep runs Init with the port ignored and, during a restart window where the fresh process's api port is still 0, Init fails and leaves the client nil — so RemoveUser panicked (recovered by the traffic writer, but re-thrown every poll) instead of returning an error. Add the same nil guard the siblings have. * fix(xray): do not revive a manually stopped Xray on a background restart RestartXray cleared isManuallyStopped unconditionally at its top, so the @30s pending-config cron (and warp/ldap/outbound reconcile jobs) that call RestartXray(false) resurrected an Xray the admin had deliberately stopped — unlike the crash-detector, which honors the manual-stop flag. Skip a non-forced restart while the stop flag is set; only an explicit forced restart clears it. * fix(xray): retry a failed pending-restart instead of dropping the config change The 30s cron consumed the need-restart flag with IsNeedRestartAndSetFalse before calling RestartXray and only logged a failure. If RestartXray failed early (a transient GetXrayConfig DB error) the old process kept running the old config, the crash detector saw a running process and never retried, and the flag stayed cleared — so an admin's saved change silently never reached the core. Move the consume/restart/retry into ApplyPendingRestart, which re-arms the flag on failure so the next tick retries. * fix(xray): synchronize the process version and apiPort fields Start writes p.version and p.apiPort (via refreshVersion/refreshAPIPort) after flipping the process to running, while GetXrayVersion and GetAPIPort read them lock-free from the status and traffic poll goroutines. The struct mutex deliberately excluded these fields, so a restart racing a poll was a real data race — a torn read of the version string header can crash. Extend the mutex to cover version and apiPort, doing the blocking version probe before taking the lock. * fix(settings): detect a wildcard listen collision between the web and sub ports The web/sub same-port check compared the two listen addresses as raw strings, so binding both on all interfaces with different spellings (webListen 0.0.0.0 vs an empty subListen) slipped past validation and only failed at startup with an opaque bind error. Treat any wildcard listen ('', 0.0.0.0, ::) as overlapping so the clash is reported up front, while still allowing two distinct specific addresses to share a port. * fix(db): mark the IP-limit cleanup seeder done on a fresh install ResetIpLimitNoFail2ban is a one-time migration that, on a host without fail2ban, zeroes every existing client's limitIp because the limit can't be enforced. It was missing from the fresh-install fast-path seeder list, so on a brand-new DB it did not run on the first boot but fired on the second — wiping any IP limits the admin had set in between. Add it to the fast-path so a truly fresh install marks it done up front (there is nothing to clean), leaving later admin-set limits intact. * fix(security): dial outbound subscriptions through the SSRF guard The outbound-subscription fetch validated the URL host once (resolving DNS and rejecting private targets) but then fetched with a plain HTTP client that re-resolves the host at dial time, so a subscription domain the attacker controls could pass validation as a public IP and rebind to 127.0.0.1 / a cloud metadata endpoint / an internal host for the actual dial — a blind SSRF into the panel's network. Route the direct fetch (and its redirects) through netsafe.SSRFGuardedDialContext, which resolves, checks and dials the same IP atomically, carrying the subscription's AllowPrivate flag on the request context; a configured egress proxy still dials its loopback bridge unguarded. * fix(security): bound the login-limiter attempts map The login rate limiter keys its records on the caller-supplied username and only evicted a record when that exact key was revisited or the login succeeded. An unauthenticated attacker replaying one CSRF token while rotating a fresh username per request seeded a record that was never revisited, growing the map without bound until the panel OOMs. Cap the map: before inserting a new record, reclaim records whose block has lapsed and whose failures aged out, and if the map is still at the ceiling under a broad flood, drop one so memory can never grow past the cap. * fix(tgbot): require admin for privileged callbacks, not just the first switch answerCallback wraps only its first callback switch in an isAdmin guard; the second switch (server usage, inbound/online enumeration, database backup export, ban logs, mass traffic reset, client creation) ran for every caller. Telegram delivers a callback with the tapping user's id, so a non-admin who can see an admin's inline keyboard — as when the bot runs in a group — could tap Backup and receive the full database and config, or reset all traffic. Default-deny before the second switch: a non-admin may only run the per-user client_* callbacks that resolve their own data from their Telegram id. * fix(eventbus): dispatch each subscriber in its own goroutine The fan-out loop called every subscriber's handler sequentially on the single dispatch goroutine. The email and Telegram notifiers block on network I/O for tens of seconds (or minutes when the remote is slow), so one slow subscriber stalled the whole loop: the 256-slot channel then filled and Publish silently dropped later events — including high-value xray.crash and node.down notifications unrelated to the slow handler. Hand each delivered event to every handler in its own goroutine so a blocking subscriber can no longer stall delivery to the others. safeCall already recovers panics, so a detached handler cannot take down the bus. * fix(integration): cap WARP API response body size doWarpRequest read the response with an unbounded io.ReadAll, unlike the sibling NordVPN client which already caps every read at maxResponseSize. A hostile panel egress proxy or a MITM on the Cloudflare WARP endpoint could stream an arbitrarily large body and force the panel into an unbounded allocation. Wrap the body in an io.LimitReader(maxResponseSize) to match the NordVPN client. * fix(email): bound every SMTP step with a connection deadline The "starttls"/"none" transport delivered through net/smtp.SendMail, which dials with an untimed net.Dial and never sets a socket deadline. When an SMTP server accepted the TCP connection but then stalled (or was a blackhole), the caller was released by Send's 30s select, but the sender goroutine and its socket stayed blocked until the OS TCP timeout — minutes per notification, leaking a goroutine and a connection each time. sendWithTLS dialed with a timeout but likewise armed no deadline on the protocol phase, and TestConnection (called synchronously from the settings handler, with no select guard) could hang the request indefinitely. Replace SendMail with sendPlain, which dials with smtpConnectTimeout and arms conn.SetDeadline(smtpDeadline) before the greeting read, preserving SendMail's opportunistic STARTTLS upgrade. Arm the same deadline in sendWithTLS and TestConnection so every SMTP step is bounded. * fix(server): guard access-log parser against malformed lines GetXrayLogs split each Xray access-log line on whitespace and then read fixed offsets — parts[1] for the timestamp and parts[i+1] after the "from", "accepted" and "email:" markers — without checking the line had that many fields. A truncated or malformed line (the logged destination is attacker-influenced) indexed past the slice and panicked; the panel handler returned a 500 via Gin's recovery. Extract the per-line field parsing into parseAccessLogFields and length guard every positional lookup so a short line yields a partial entry instead of panicking. * fix(server): guard xray key-generator output parsing GetNewX25519Cert, GetNewmldsa65 and GetNewmlkem768 parsed xray's stdout by reading lines[0], lines[1] and each line's second colon-separated field without any length check — unlike GetNewEchCert, which already guards its line count. If the xray binary printed fewer than two lines or reformatted its labels (a version change, or a silent failure that emitted nothing), the fixed slice index panicked and the handler 500'd. Extract the shared parsing into parseXrayKeyPairOutput, which length guards the line count and each label split and returns an error instead of panicking, then route all three generators through it. * fix(tgbot): stop auto-deleted messages from resetting wizard state SendMsgToTgbotDeleteAfter spawns a goroutine that, after the display delay, deleted the transient message and then unconditionally cleared the chat's conversation state. Every caller that ends a wizard step already clears the state synchronously, so that call was redundant — and harmful: if within the delay the user advanced to the next step (a callback sets a fresh awaiting_* state), the late goroutine wiped it, and the user's next message fell through unrecognized, silently dropping their input. Move the delayed deletion into deleteMessageAfterDelay, which only removes the message and no longer touches the conversation state. Guard deleteMessageTgBot against a nil bot so the deletion path is unit-testable. * fix(frontend): refetch a fresh CSRF token on 403 instead of reusing the stale meta tag On a 403 to an unsafe method the client cleared its cached CSRF token and called ensureCsrfToken to retry. But ensureCsrfToken prefers the <meta name="csrf-token"> tag baked into the page, which the production panel always injects, so the "refresh" re-read the same stale token and the /csrf-token refetch was never reached — the retry re-sent the token that had just been rejected and the save failed with an error toast. The token lives in the session and rotates when the session is regenerated (for example re-login in another tab), leaving the tab's baked-in meta token stale. Fetch the current token straight from /csrf-token in the 403 branch so the retry uses the authoritative server value. The existing tests only passed because they strip the meta tag; the new test keeps a stale tag present. * fix(frontend): surface backend error text from failed requests HttpUtil.get/post read the thrown HttpError body as response.data.message, but the backend error envelope (entity.Msg) serializes its text as msg. On any non-2xx JSON response the real reason was therefore dropped and the operator saw only the generic "Request failed with status N" toast. Read response.data.msg first (keeping message and the native error text as fallbacks). The sibling test had pinned the wrong body shape ({ message }); correct it to the real backend shape ({ success:false, msg }) so it exercises the actual envelope. * fix(frontend): share one WebSocket connection across bridge and hooks websocketBridge.ts and useWebSocket.ts each declared their own module-scoped sharedClient plus an identical getSharedClient, so the "shared" client was not shared between them: whenever a page using useWebSocket (Clients/Inbounds) mounted alongside the always-mounted bridge, the panel opened two sockets to /ws. The server then pushed every traffic/stats/nodes/inbounds snapshot to both, doubling WebSocket bandwidth and running two independent reconnect loops, and the hook's socket was never disconnected on unmount. Hoist a single getSharedWebSocketClient into api/websocket.ts and route both the bridge and the hook through it, so exactly one connection is opened. * fix(frontend): guard the outbounds WebSocket handler against non-array payloads onOutbounds wrote the raw WebSocket payload straight into the outboundsTraffic cache, unlike the sibling onNodes/onInbounds handlers which first check Array.isArray. A malformed non-array push (for example an object) would land in the cache with staleTime Infinity; consumers that call .find()/.map() on the outbounds list would then throw and crash the Outbounds tab. Add the same Array.isArray guard so a bad push is ignored. * fix(frontend): key the node table by the computed row key, not id The desktop node table used rowKey="id", but transitive sub-nodes (the read-only rows surfaced from downstream nodes) all carry id 0, so a topology with two or more transitive rows gave React duplicate keys. antd's rowKey prop overrides the row object's own computed `key` (`t-${guid}` for transitive rows, the numeric id otherwise), so the unique key the code already builds was ignored — causing row-state/DOM mis-association on any re-render (heartbeat refetch, address-eye toggle). The mobile card path already keyed by record.key. Key the table by "key" so transitive rows get their distinct t-${guid} identity; direct nodes keep key === id, so row selection (filtered to numeric keys) is unchanged. * fix(frontend): map routing row actions through the rule's real index The routing table hides balancer-loopback rules (`_bl_*`) but keeps each visible row's original index in `key`, then handed antd's positional row index straight to edit/delete/toggle/move/drag — all of which mutate the full, unfiltered routing.rules array. Once a hidden loopback rule precedes a visible one (e.g. a balancer whose fallback is another balancer, plus any rule added afterwards), the positional index no longer matches the array index, so deleting or editing a rule silently hit the wrong one — including destroying the loopback rule that keeps the balancer alive. Add originalRuleIndex to translate a positional row index back through the row's `key`, and route every mutating handler (openEdit, confirmDelete, toggleRule, moveUp/moveDown, drag) through it. When no loopback rows are hidden the mapping is the identity, so ordinary configs are unaffected. * fix(frontend): map outbound row actions through the outbound's real index The outbounds table hides balancer-loopback outbounds (`_bl_*`) but keeps each visible row's original index in `key`, then passed antd's positional row index to edit/delete/move and to the per-row probe (onTest) and its result lookup — all of which address the full, unfiltered outbounds array. Once a hidden loopback outbound precedes a visible one, the positional index diverges from the array index, so deleting or editing an outbound hit the wrong one (its deletion-impact plan and removal targeting the wrong entry), and the test button probed / showed results against the wrong outbound. Add originalOutboundIndex and route the mutating handlers through it; key the probe trigger and test-result columns by record.key. With no loopback rows hidden the mapping is the identity, so ordinary configs are unaffected. * fix(frontend): tolerate a malformed happyEyeballs value in the Xray Basics tab BasicsTab derived directHappyEyeballs by calling HappyEyeballsSchema.parse during render, guarding only against null/non-object. A wrong-typed field (e.g. happyEyeballs.tryDelayMs as a string) or any other shape mismatch — reachable via the Complete Template JSON editor or an imported config — threw straight out of render, white-screening the default Xray landing tab. Use safeParse and fall back to null so a bad value degrades to "no override" instead of crashing the page. * fix(frontend): preserve routing-rule fields the form does not surface The rule form rebuilt the rule from a fixed literal of only the fields it edits, and RoutingTab replaces the rule wholesale on confirm. Fields the form never exposes — localPort, localIP, process, ruleTag, webhook — are in the rule schema and can arrive via the advanced JSON editor or Import Rules; opening such a rule in the form and saving silently dropped them. Carry over every key of the original rule the form does not manage before applying the form-derived fields, so an edit only touches what it surfaces. * fix(frontend): re-sync the sniffing island when its value changes externally The sniffing config editor froze its seed value at mount and only watched its own inner AntD form, never reflecting a later change to the shared RHF `sniffing` path. Because the inbound form mounts every tab with forceRender, the friendly Sniffing tab and the Advanced JSON editor are live at once: editing sniffing in the JSON editor updated the RHF value but not the frozen island, so the next interaction with the friendly tab emitted the stale value and silently discarded the JSON edit. Add an effect that pushes an external value change into the inner form, guarded by the same lastEmitted marker the emit path uses so the island never re-seeds from its own echo and no update loop forms. * fix(frontend): don't drift a client's byte quota on a no-op save The quota field shows the total in GB rounded to two decimals; editing a client and saving converted that display value straight back to bytes. A byte total not aligned to 0.01 GB — one set via the API or an import — was therefore rewritten to the rounded value on any save that never touched the field, losing a few MB each time. Add resolveTotalBytes: keep the original byte total when the displayed GB still matches it, and only re-derive from GB when the user actually changed the field. * fix(eventbus): deliver events on a bounded per-subscriber worker The previous fix dispatched each event to every subscriber with a bare `go safeCall`. That unblocked the dispatch loop, but removed the bus's backpressure: under a login-attempt flood (which both notifier subscribers process without rate-limiting) with email/Telegram enabled, every attempt spawned handler goroutines that each block on network I/O for up to ~30s, with no bound — a goroutine and outbound-connection storm. It also let a subscriber's handler run concurrently with itself, racing the Telegram notifier's lazily-cached hostname. Give each subscriber its own bounded queue drained by a single worker goroutine. Dispatch does a non-blocking send per subscriber (dropping only that subscriber's event when its queue is full), so a slow subscriber still can't stall the others, concurrency is bounded to one in-flight handler per subscriber, per-subscriber event order is preserved, and Stop again waits for in-flight handlers to finish. * fix(frontend): map outbound mobile-card actions through the real index too The desktop outbounds table was keyed by the outbound's real index, but the mobile card list was left keying the probe trigger and every test-state lookup by the positional row index. With a hidden balancer-loopback outbound present, tapping Check on a mobile card probed the wrong outbound and the Test-All results landed on the wrong card. Key onTest and the testResult/isTesting reads by record.key, matching the desktop columns. * fix(frontend): meet WCAG AA contrast on the config-block link text The Storybook accessibility test flagged the share-link <code> block: with no explicit color it inherited a muted grey that renders as #888888 on the #f8f8f8 tertiary-fill background in CI's Chromium — a 3.33:1 contrast, below the 4.5:1 AA threshold. Set the text to the theme's primary text token so the colour is explicit and high-contrast in both light and dark themes instead of depending on an inherited value that varies by browser. * style(sub): simplify a negated conjunction to satisfy staticcheck QF1001 golangci-lint (staticcheck QF1001) flagged the `!(a && b)` guard in expandSegment. Rewrite it via De Morgan's law to the equivalent `!a || !b` form so the linter passes; behavior is unchanged. * fix: close panics and races the audit's own fixes left nearby Second-pass review of the 54-commit self-correcting audit. Each item below was confirmed by reading the surrounding source (and, where practical, the pre-fix code) before being changed; regression tests are included for every behavioral fix. Concurrency: - eventbus: Bus.Subscribe called wg.Add with no synchronization against a concurrent Bus.Stop's wg.Wait, a real "WaitGroup misuse" panic risk (e.g. a Telegram-bot settings save racing panel shutdown/restart). Stop now flips a mu-guarded `stopped` flag before waiting, and Subscribe checks it under the same lock, so Add and Wait can no longer race. Security: - login_limiter: evictForRoom's fallback eviction picked an arbitrary map key, including ones still under an active cooldown - an attacker flooding /login with fresh usernames could evict their own (or anyone's) blocked record and reset the lockout. The fallback now skips actively-blocked records, only falling back to an unconditional evict if the map is somehow entirely full of active blocks (preserves the hard memory cap). Subscription-endpoint panics (reachable by any client hitting /sub): - internal/sub/service.go: applyPathAndHostParams/Obj (ws/httpupgrade/xhttp with no path settings object) and the TLS alpn readers in three places used unchecked type assertions - exactly the bug classabab7cd0patched elsewhere in the same switch statements, just not these call sites. - internal/sub/json_service.go, clash_service.go: the externalProxy loops in the JSON and Clash generators used unchecked assertions on a legacy/admin-supplied field (missing "port", non-object entry, etc.). - internal/sub/json_service.go: realityData's shortId/serverName selection could assert a non-string array element. Other correctness: - client_traffic.go: ResetAllTraffics (touched by3eb214d0) still skipped clearing NodeClientTraffic node-sync baselines, unlike its sibling reset paths in the same file - a node's next sync would re-add pre-reset delta on top of the freshly-zeroed counter. - inbound_traffic.go: the traffic-tick tx's Commit/Rollback errors were silently discarded; now logged so a backend-level commit failure (e.g. an aborted Postgres tx from a best-effort helper) doesn't masquerade as a successful tick. - outbound_subscription.go: the new subscriptionFetchClient doc comment was wedged between fetchAndStore's existing comment and fetchAndStore itself, leaving fetchAndStore undocumented and the comment describing the wrong function. Convention cleanup: - Removed narrative // comments added by the audit that violate this repo's no-inline-comment rule (mostly narrating the specific bug/fix rather than a lasting contract, and mostly on new Test functions, which this repo's existing tests never comment) - calibrated against this exact codebase's own pre-existing comment style so legitimate godoc-style doc comments were left alone. --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2408 lines
70 KiB
Go
2408 lines
70 KiB
Go
package service
|
|
|
|
import (
|
|
"archive/zip"
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
stdnet "net"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/sys"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
|
|
"github.com/google/uuid"
|
|
utls "github.com/refraction-networking/utls"
|
|
"github.com/shirou/gopsutil/v4/cpu"
|
|
"github.com/shirou/gopsutil/v4/disk"
|
|
"github.com/shirou/gopsutil/v4/host"
|
|
"github.com/shirou/gopsutil/v4/load"
|
|
"github.com/shirou/gopsutil/v4/mem"
|
|
"github.com/shirou/gopsutil/v4/net"
|
|
)
|
|
|
|
// ProcessState represents the current state of a system process.
|
|
type ProcessState string
|
|
|
|
// Process state constants
|
|
const (
|
|
Running ProcessState = "running" // Process is running normally
|
|
Stop ProcessState = "stop" // Process is stopped
|
|
Error ProcessState = "error" // Process is in error state
|
|
)
|
|
|
|
// Status represents comprehensive system and application status information.
|
|
// It includes CPU, memory, disk, network statistics, and Xray process status.
|
|
type Status struct {
|
|
T time.Time `json:"-"`
|
|
Cpu float64 `json:"cpu"`
|
|
CpuCores int `json:"cpuCores"`
|
|
LogicalPro int `json:"logicalPro"`
|
|
CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
|
|
Mem struct {
|
|
Current uint64 `json:"current"`
|
|
Total uint64 `json:"total"`
|
|
} `json:"mem"`
|
|
Swap struct {
|
|
Current uint64 `json:"current"`
|
|
Total uint64 `json:"total"`
|
|
} `json:"swap"`
|
|
Disk struct {
|
|
Current uint64 `json:"current"`
|
|
Total uint64 `json:"total"`
|
|
} `json:"disk"`
|
|
DiskIO struct {
|
|
Read uint64 `json:"read"`
|
|
Write uint64 `json:"write"`
|
|
} `json:"diskIO"`
|
|
DiskTraffic struct {
|
|
Read uint64 `json:"read"`
|
|
Write uint64 `json:"write"`
|
|
} `json:"diskTraffic"`
|
|
Xray struct {
|
|
State ProcessState `json:"state"`
|
|
ErrorMsg string `json:"errorMsg"`
|
|
Version string `json:"version"`
|
|
} `json:"xray"`
|
|
PanelVersion string `json:"panelVersion"`
|
|
PanelGuid string `json:"panelGuid"`
|
|
Uptime uint64 `json:"uptime"`
|
|
Loads []float64 `json:"loads"`
|
|
TcpCount int `json:"tcpCount"`
|
|
UdpCount int `json:"udpCount"`
|
|
NetIO struct {
|
|
Up uint64 `json:"up"`
|
|
Down uint64 `json:"down"`
|
|
PktUp uint64 `json:"pktUp"`
|
|
PktDown uint64 `json:"pktDown"`
|
|
} `json:"netIO"`
|
|
NetTraffic struct {
|
|
Sent uint64 `json:"sent"`
|
|
Recv uint64 `json:"recv"`
|
|
PktSent uint64 `json:"pktSent"`
|
|
PktRecv uint64 `json:"pktRecv"`
|
|
} `json:"netTraffic"`
|
|
PublicIP struct {
|
|
IPv4 string `json:"ipv4"`
|
|
IPv6 string `json:"ipv6"`
|
|
} `json:"publicIP"`
|
|
AppStats struct {
|
|
Threads uint32 `json:"threads"`
|
|
Mem uint64 `json:"mem"`
|
|
Uptime uint64 `json:"uptime"`
|
|
} `json:"appStats"`
|
|
}
|
|
|
|
// Release represents information about a software release from GitHub.
|
|
type Release struct {
|
|
TagName string `json:"tag_name"` // The tag name of the release
|
|
Body string `json:"body"` // The release notes; the dev channel reads its commit from here
|
|
TargetCommitish string `json:"target_commitish"` // The branch/commit the tag points at
|
|
Prerelease bool `json:"prerelease"` // Whether this is a pre-release
|
|
}
|
|
|
|
// ServerService provides business logic for server monitoring and management.
|
|
// It handles system status collection, IP detection, and application statistics.
|
|
type ServerService struct {
|
|
xrayService XrayService
|
|
inboundService InboundService
|
|
settingService SettingService
|
|
cachedIPv4 string
|
|
cachedIPv6 string
|
|
noIPv6 bool
|
|
mu sync.Mutex
|
|
lastCPUTimes cpu.TimesStat
|
|
hasLastCPUSample bool
|
|
hasNativeCPUSample bool
|
|
emaCPU float64
|
|
cachedCpuSpeedMhz float64
|
|
lastCpuInfoAttempt time.Time
|
|
|
|
lastStatusMu sync.RWMutex
|
|
lastStatus *Status
|
|
|
|
versionsCacheMu sync.Mutex
|
|
versionsCache *cachedXrayVersions
|
|
|
|
fail2banMu sync.Mutex
|
|
fail2banInstalled bool
|
|
fail2banCheckedAt time.Time
|
|
}
|
|
|
|
type cachedXrayVersions struct {
|
|
versions []string
|
|
fetchedAt time.Time
|
|
}
|
|
|
|
// xrayVersionsCacheTTL bounds how often /getXrayVersion hits GitHub. The list
|
|
// is purely informational (rendered in the "switch Xray version" picker) so a
|
|
// quarter-hour staleness window is fine and saves the API budget.
|
|
const xrayVersionsCacheTTL = 15 * time.Minute
|
|
|
|
// allowedHistoryBuckets is the bucket-second whitelist for time-series
|
|
// aggregation endpoints (server + node metrics). Restricting it prevents
|
|
// callers from triggering arbitrary aggregation work and keeps the
|
|
// frontend's bucket selector self-documenting.
|
|
var allowedHistoryBuckets = map[int]bool{
|
|
2: true, // 2m
|
|
30: true, // 30m
|
|
60: true, // 1h
|
|
180: true, // 3h
|
|
360: true, // 6h
|
|
720: true, // 12h
|
|
1440: true, // 24h
|
|
2880: true, // 2d
|
|
10080: true, // 7d
|
|
}
|
|
|
|
// IsAllowedHistoryBucket reports whether a bucket-seconds value is in the
|
|
// whitelist used by /server/history, /server/cpuHistory, /server/xrayMetricsHistory,
|
|
// /server/xrayObservatoryHistory, and /nodes/history.
|
|
func IsAllowedHistoryBucket(bucketSeconds int) bool {
|
|
return allowedHistoryBuckets[bucketSeconds]
|
|
}
|
|
|
|
// LastStatus returns the most recent Status snapshot collected by
|
|
// RefreshStatus. Safe for concurrent readers.
|
|
func (s *ServerService) LastStatus() *Status {
|
|
s.lastStatusMu.RLock()
|
|
defer s.lastStatusMu.RUnlock()
|
|
return s.lastStatus
|
|
}
|
|
|
|
// Fail2banStatus tells the frontend whether the per-client IP limit can
|
|
// actually be enforced. Enforcement depends on fail2ban, so a limit set
|
|
// without it would silently do nothing.
|
|
type Fail2banStatus struct {
|
|
Enabled bool `json:"enabled"`
|
|
Installed bool `json:"installed"`
|
|
Usable bool `json:"usable"`
|
|
Windows bool `json:"windows"`
|
|
}
|
|
|
|
const fail2banInstalledCacheTTL = 30 * time.Second
|
|
|
|
func (s *ServerService) GetFail2banStatus() Fail2banStatus {
|
|
enabled := isFail2banEnabled()
|
|
|
|
installed := false
|
|
if enabled {
|
|
installed = s.isFail2banInstalled()
|
|
}
|
|
|
|
return Fail2banStatus{
|
|
Enabled: enabled,
|
|
Installed: installed,
|
|
Usable: enabled && installed,
|
|
Windows: runtime.GOOS == "windows",
|
|
}
|
|
}
|
|
|
|
func isFail2banEnabled() bool {
|
|
value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
|
|
return !ok || value == "true"
|
|
}
|
|
|
|
func (s *ServerService) isFail2banInstalled() bool {
|
|
s.fail2banMu.Lock()
|
|
defer s.fail2banMu.Unlock()
|
|
|
|
if !s.fail2banCheckedAt.IsZero() && time.Since(s.fail2banCheckedAt) < fail2banInstalledCacheTTL {
|
|
return s.fail2banInstalled
|
|
}
|
|
|
|
err := exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run()
|
|
s.fail2banInstalled = err == nil
|
|
s.fail2banCheckedAt = time.Now()
|
|
return s.fail2banInstalled
|
|
}
|
|
|
|
// RefreshStatus collects a new system snapshot, stores it as LastStatus, and
|
|
// appends it to the system-metrics time series. Returns the new snapshot (may
|
|
// be nil if collection failed). Called by the background ticker; the caller is
|
|
// responsible for any side effects (websocket broadcast, xray metrics sample).
|
|
func (s *ServerService) RefreshStatus() *Status {
|
|
next := s.GetStatus(s.LastStatus())
|
|
if next == nil {
|
|
return nil
|
|
}
|
|
s.lastStatusMu.Lock()
|
|
s.lastStatus = next
|
|
s.lastStatusMu.Unlock()
|
|
s.AppendStatusSample(time.Now(), next)
|
|
return next
|
|
}
|
|
|
|
// GetXrayVersionsCached wraps GetXrayVersions with a TTL cache. On fetch
|
|
// failure we serve the last successful list (if any) so the UI doesn't go
|
|
// blank during a GitHub API hiccup; if there's no cache at all the underlying
|
|
// error is surfaced.
|
|
func (s *ServerService) GetXrayVersionsCached() ([]string, error) {
|
|
s.versionsCacheMu.Lock()
|
|
cache := s.versionsCache
|
|
s.versionsCacheMu.Unlock()
|
|
if cache != nil && time.Since(cache.fetchedAt) <= xrayVersionsCacheTTL {
|
|
return cache.versions, nil
|
|
}
|
|
versions, err := s.GetXrayVersions()
|
|
if err != nil {
|
|
if cache != nil {
|
|
logger.Warning("GetXrayVersionsCached: serving stale list:", err)
|
|
return cache.versions, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
s.versionsCacheMu.Lock()
|
|
s.versionsCache = &cachedXrayVersions{versions: versions, fetchedAt: time.Now()}
|
|
s.versionsCacheMu.Unlock()
|
|
return versions, nil
|
|
}
|
|
|
|
// GetDefaultLogOutboundTags scans the default Xray config for freedom and
|
|
// blackhole outbound tags so /getXrayLogs can colour-code log lines without
|
|
// the controller re-doing the JSON walk. Falls back to the historical
|
|
// "direct"/"blocked" defaults when the config can't be read.
|
|
func (s *ServerService) GetDefaultLogOutboundTags() (freedoms, blackholes []string) {
|
|
config, err := s.settingService.GetDefaultXrayConfig()
|
|
if err == nil && config != nil {
|
|
if cfgMap, ok := config.(map[string]any); ok {
|
|
if outbounds, ok := cfgMap["outbounds"].([]any); ok {
|
|
for _, outbound := range outbounds {
|
|
obMap, ok := outbound.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
tag, _ := obMap["tag"].(string)
|
|
if tag == "" {
|
|
continue
|
|
}
|
|
switch obMap["protocol"] {
|
|
case "freedom":
|
|
freedoms = append(freedoms, tag)
|
|
case "blackhole":
|
|
blackholes = append(blackholes, tag)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if len(freedoms) == 0 {
|
|
freedoms = []string{"direct"}
|
|
}
|
|
if len(blackholes) == 0 {
|
|
blackholes = []string{"blocked"}
|
|
}
|
|
return freedoms, blackholes
|
|
}
|
|
|
|
// AggregateCpuHistory returns up to maxPoints averaged buckets of size bucketSeconds.
|
|
// Kept for back-compat with the original /panel/api/server/cpuHistory/:bucket route;
|
|
// the response key is "cpu" (not "v") so legacy consumers parse unchanged.
|
|
func (s *ServerService) AggregateCpuHistory(bucketSeconds int, maxPoints int) []map[string]any {
|
|
out := systemMetrics.aggregate("cpu", bucketSeconds, maxPoints)
|
|
for _, p := range out {
|
|
p["cpu"] = p["v"]
|
|
delete(p, "v")
|
|
}
|
|
return out
|
|
}
|
|
|
|
// AggregateSystemMetric returns up to maxPoints averaged buckets for any
|
|
// known system metric (see SystemMetricKeys). Output points have keys
|
|
// {"t": unixSec, "v": value}; the caller decides how to format the value.
|
|
func (s *ServerService) AggregateSystemMetric(metric string, bucketSeconds int, maxPoints int) []map[string]any {
|
|
return systemMetrics.aggregate(metric, bucketSeconds, maxPoints)
|
|
}
|
|
|
|
type LogEntry struct {
|
|
DateTime time.Time
|
|
FromAddress string
|
|
ToAddress string
|
|
Inbound string
|
|
Outbound string
|
|
Email string
|
|
Event int
|
|
}
|
|
|
|
func getPublicIP(url string) string {
|
|
client := &http.Client{
|
|
Timeout: 3 * time.Second,
|
|
}
|
|
|
|
req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
|
|
if reqErr != nil {
|
|
return "N/A"
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "N/A"
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// Don't retry if access is blocked or region-restricted
|
|
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnavailableForLegalReasons {
|
|
return "N/A"
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "N/A"
|
|
}
|
|
|
|
ip, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "N/A"
|
|
}
|
|
|
|
ipString := strings.TrimSpace(string(ip))
|
|
if ipString == "" {
|
|
return "N/A"
|
|
}
|
|
|
|
return ipString
|
|
}
|
|
|
|
var publicIPv4Services = []string{
|
|
"https://api4.ipify.org",
|
|
"https://ipv4.icanhazip.com",
|
|
"https://v4.api.ipinfo.io/ip",
|
|
"https://ipv4.myexternalip.com/raw",
|
|
"https://4.ident.me",
|
|
"https://check-host.net/ip",
|
|
}
|
|
|
|
var publicIPv6Services = []string{
|
|
"https://api6.ipify.org",
|
|
"https://ipv6.icanhazip.com",
|
|
"https://v6.api.ipinfo.io/ip",
|
|
"https://ipv6.myexternalip.com/raw",
|
|
"https://6.ident.me",
|
|
}
|
|
|
|
// resolvePublicIPs caches the public IPv4/IPv6 addresses on first use. Guarded
|
|
// by s.mu because the bot's ServerService may call it from sendBackup while a
|
|
// status report runs concurrently.
|
|
func (s *ServerService) resolvePublicIPs() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if s.cachedIPv4 == "" {
|
|
for _, ip4Service := range publicIPv4Services {
|
|
s.cachedIPv4 = getPublicIP(ip4Service)
|
|
if s.cachedIPv4 != "N/A" {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if s.cachedIPv6 == "" && !s.noIPv6 {
|
|
for _, ip6Service := range publicIPv6Services {
|
|
s.cachedIPv6 = getPublicIP(ip6Service)
|
|
if s.cachedIPv6 != "N/A" {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if s.cachedIPv6 == "N/A" {
|
|
s.noIPv6 = true
|
|
}
|
|
}
|
|
|
|
func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
|
now := time.Now()
|
|
status := &Status{
|
|
T: now,
|
|
}
|
|
|
|
// CPU stats
|
|
util, err := s.sampleCPUUtilization()
|
|
if err != nil {
|
|
logger.Warning("get cpu percent failed:", err)
|
|
} else {
|
|
status.Cpu = util
|
|
}
|
|
|
|
status.CpuCores, err = cpu.Counts(false)
|
|
if err != nil {
|
|
logger.Warning("get cpu cores count failed:", err)
|
|
}
|
|
|
|
status.LogicalPro = runtime.NumCPU()
|
|
|
|
if status.CpuSpeedMhz = s.cachedCpuSpeedMhz; s.cachedCpuSpeedMhz == 0 && time.Since(s.lastCpuInfoAttempt) > 5*time.Minute {
|
|
s.lastCpuInfoAttempt = time.Now()
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
cpuInfos, err := cpu.Info()
|
|
if err != nil {
|
|
logger.Warning("get cpu info failed:", err)
|
|
return
|
|
}
|
|
if len(cpuInfos) > 0 {
|
|
s.cachedCpuSpeedMhz = cpuInfos[0].Mhz
|
|
status.CpuSpeedMhz = s.cachedCpuSpeedMhz
|
|
} else {
|
|
logger.Warning("could not find cpu info")
|
|
}
|
|
}()
|
|
select {
|
|
case <-done:
|
|
case <-time.After(1500 * time.Millisecond):
|
|
logger.Warning("cpu info query timed out; will retry later")
|
|
}
|
|
} else if s.cachedCpuSpeedMhz != 0 {
|
|
status.CpuSpeedMhz = s.cachedCpuSpeedMhz
|
|
}
|
|
|
|
// Uptime
|
|
upTime, err := host.Uptime()
|
|
if err != nil {
|
|
logger.Warning("get uptime failed:", err)
|
|
} else {
|
|
status.Uptime = upTime
|
|
}
|
|
|
|
// Memory stats
|
|
memInfo, err := mem.VirtualMemory()
|
|
if err != nil {
|
|
logger.Warning("get virtual memory failed:", err)
|
|
} else {
|
|
status.Mem.Current = memInfo.Used
|
|
status.Mem.Total = memInfo.Total
|
|
}
|
|
|
|
swapInfo, err := mem.SwapMemory()
|
|
if err != nil {
|
|
logger.Warning("get swap memory failed:", err)
|
|
} else {
|
|
status.Swap.Current = swapInfo.Used
|
|
status.Swap.Total = swapInfo.Total
|
|
}
|
|
|
|
// Disk stats
|
|
diskInfo, err := disk.Usage("/")
|
|
if err != nil {
|
|
logger.Warning("get disk usage failed:", err)
|
|
} else {
|
|
status.Disk.Current = diskInfo.Used
|
|
status.Disk.Total = diskInfo.Total
|
|
}
|
|
|
|
diskIOStats, err := disk.IOCounters()
|
|
if err != nil {
|
|
logger.Warning("get disk io counters failed:", err)
|
|
} else {
|
|
var totalRead, totalWrite uint64
|
|
for _, counter := range diskIOStats {
|
|
totalRead += counter.ReadBytes
|
|
totalWrite += counter.WriteBytes
|
|
}
|
|
status.DiskTraffic.Read = totalRead
|
|
status.DiskTraffic.Write = totalWrite
|
|
|
|
if lastStatus != nil {
|
|
duration := now.Sub(lastStatus.T)
|
|
seconds := float64(duration) / float64(time.Second)
|
|
if seconds > 0 && status.DiskTraffic.Read >= lastStatus.DiskTraffic.Read {
|
|
status.DiskIO.Read = uint64(float64(status.DiskTraffic.Read-lastStatus.DiskTraffic.Read) / seconds)
|
|
}
|
|
if seconds > 0 && status.DiskTraffic.Write >= lastStatus.DiskTraffic.Write {
|
|
status.DiskIO.Write = uint64(float64(status.DiskTraffic.Write-lastStatus.DiskTraffic.Write) / seconds)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Load averages
|
|
avgState, err := load.Avg()
|
|
if err != nil {
|
|
logger.Warning("get load avg failed:", err)
|
|
} else {
|
|
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
|
|
}
|
|
|
|
// Network stats
|
|
ioStats, err := net.IOCounters(true)
|
|
if err != nil {
|
|
logger.Warning("get io counters failed:", err)
|
|
} else {
|
|
var totalSent, totalRecv, totalPktSent, totalPktRecv uint64
|
|
for _, iface := range ioStats {
|
|
name := strings.ToLower(iface.Name)
|
|
if isVirtualInterface(name) {
|
|
continue
|
|
}
|
|
totalSent += iface.BytesSent
|
|
totalRecv += iface.BytesRecv
|
|
totalPktSent += iface.PacketsSent
|
|
totalPktRecv += iface.PacketsRecv
|
|
}
|
|
status.NetTraffic.Sent = totalSent
|
|
status.NetTraffic.Recv = totalRecv
|
|
status.NetTraffic.PktSent = totalPktSent
|
|
status.NetTraffic.PktRecv = totalPktRecv
|
|
|
|
if lastStatus != nil {
|
|
duration := now.Sub(lastStatus.T)
|
|
seconds := float64(duration) / float64(time.Second)
|
|
up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
|
|
down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
|
|
status.NetIO.Up = up
|
|
status.NetIO.Down = down
|
|
if seconds > 0 && status.NetTraffic.PktSent >= lastStatus.NetTraffic.PktSent {
|
|
status.NetIO.PktUp = uint64(float64(status.NetTraffic.PktSent-lastStatus.NetTraffic.PktSent) / seconds)
|
|
}
|
|
if seconds > 0 && status.NetTraffic.PktRecv >= lastStatus.NetTraffic.PktRecv {
|
|
status.NetIO.PktDown = uint64(float64(status.NetTraffic.PktRecv-lastStatus.NetTraffic.PktRecv) / seconds)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TCP/UDP connections
|
|
status.TcpCount, err = sys.GetTCPCount()
|
|
if err != nil {
|
|
logger.Warning("get tcp connections failed:", err)
|
|
}
|
|
|
|
status.UdpCount, err = sys.GetUDPCount()
|
|
if err != nil {
|
|
logger.Warning("get udp connections failed:", err)
|
|
}
|
|
|
|
s.resolvePublicIPs()
|
|
status.PublicIP.IPv4 = s.cachedIPv4
|
|
status.PublicIP.IPv6 = s.cachedIPv6
|
|
|
|
// Xray status
|
|
if s.xrayService.IsXrayRunning() {
|
|
status.Xray.State = Running
|
|
status.Xray.ErrorMsg = ""
|
|
} else {
|
|
err := s.xrayService.GetXrayErr()
|
|
if err != nil {
|
|
status.Xray.State = Error
|
|
} else {
|
|
status.Xray.State = Stop
|
|
}
|
|
status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
|
|
}
|
|
status.Xray.Version = s.xrayService.GetXrayVersion()
|
|
status.PanelVersion = config.GetPanelVersion()
|
|
if guid, err := s.settingService.GetPanelGuid(); err == nil {
|
|
status.PanelGuid = guid
|
|
}
|
|
|
|
// Application stats
|
|
if rss := sys.SelfRSS(); rss > 0 {
|
|
status.AppStats.Mem = rss
|
|
} else {
|
|
var rtm runtime.MemStats
|
|
runtime.ReadMemStats(&rtm)
|
|
status.AppStats.Mem = rtm.Sys
|
|
}
|
|
status.AppStats.Threads = uint32(runtime.NumGoroutine())
|
|
if p != nil && p.IsRunning() {
|
|
status.AppStats.Uptime = p.GetUptime()
|
|
} else {
|
|
status.AppStats.Uptime = 0
|
|
}
|
|
|
|
return status
|
|
}
|
|
|
|
// AppendCpuSample is preserved for callers that only have the CPU number.
|
|
// New callers should prefer AppendStatusSample which writes the full set.
|
|
func (s *ServerService) AppendCpuSample(t time.Time, v float64) {
|
|
systemMetrics.append("cpu", t, v)
|
|
}
|
|
|
|
// AppendStatusSample writes one tick of every metric we keep — CPU, memory
|
|
// percent, network throughput (bytes/s), online client count, and the three
|
|
// load averages. Called by RefreshStatus on the same @2s cadence as
|
|
// AppendCpuSample, so all series stay aligned.
|
|
func (s *ServerService) AppendStatusSample(t time.Time, status *Status) {
|
|
if status == nil {
|
|
return
|
|
}
|
|
systemMetrics.append("cpu", t, status.Cpu)
|
|
if status.Mem.Total > 0 {
|
|
systemMetrics.append("mem", t, float64(status.Mem.Current)*100.0/float64(status.Mem.Total))
|
|
}
|
|
if status.Swap.Total > 0 {
|
|
systemMetrics.append("swap", t, float64(status.Swap.Current)*100.0/float64(status.Swap.Total))
|
|
} else {
|
|
systemMetrics.append("swap", t, 0)
|
|
}
|
|
systemMetrics.append("netUp", t, float64(status.NetIO.Up))
|
|
systemMetrics.append("netDown", t, float64(status.NetIO.Down))
|
|
systemMetrics.append("diskRead", t, float64(status.DiskIO.Read))
|
|
systemMetrics.append("diskWrite", t, float64(status.DiskIO.Write))
|
|
if status.Disk.Total > 0 {
|
|
systemMetrics.append("diskUsage", t, float64(status.Disk.Current)*100.0/float64(status.Disk.Total))
|
|
}
|
|
systemMetrics.append("pktUp", t, float64(status.NetIO.PktUp))
|
|
systemMetrics.append("pktDown", t, float64(status.NetIO.PktDown))
|
|
systemMetrics.append("tcpCount", t, float64(status.TcpCount))
|
|
systemMetrics.append("udpCount", t, float64(status.UdpCount))
|
|
online := 0
|
|
if p != nil && p.IsRunning() {
|
|
online = len(p.GetOnlineClients())
|
|
}
|
|
systemMetrics.append("online", t, float64(online))
|
|
if len(status.Loads) >= 3 {
|
|
systemMetrics.append("load1", t, status.Loads[0])
|
|
systemMetrics.append("load5", t, status.Loads[1])
|
|
systemMetrics.append("load15", t, status.Loads[2])
|
|
}
|
|
}
|
|
|
|
func (s *ServerService) sampleCPUUtilization() (float64, error) {
|
|
// Try native platform-specific CPU implementation first (Windows, Linux, macOS)
|
|
if pct, err := sys.CPUPercentRaw(); err == nil {
|
|
s.mu.Lock()
|
|
// First call to native method returns 0 (initializes baseline)
|
|
if !s.hasNativeCPUSample {
|
|
s.hasNativeCPUSample = true
|
|
s.mu.Unlock()
|
|
return 0, nil
|
|
}
|
|
// Smooth with EMA
|
|
const alpha = 0.3
|
|
if s.emaCPU == 0 {
|
|
s.emaCPU = pct
|
|
} else {
|
|
s.emaCPU = alpha*pct + (1-alpha)*s.emaCPU
|
|
}
|
|
val := s.emaCPU
|
|
s.mu.Unlock()
|
|
return val, nil
|
|
}
|
|
// If native call fails, fall back to gopsutil times
|
|
// Read aggregate CPU times (all CPUs combined)
|
|
times, err := cpu.Times(false)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if len(times) == 0 {
|
|
return 0, fmt.Errorf("no cpu times available")
|
|
}
|
|
|
|
cur := times[0]
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
// If this is the first sample, initialize and return current EMA (0 by default)
|
|
if !s.hasLastCPUSample {
|
|
s.lastCPUTimes = cur
|
|
s.hasLastCPUSample = true
|
|
return s.emaCPU, nil
|
|
}
|
|
|
|
// Compute busy and total deltas
|
|
// Note: Guest and GuestNice times are already included in User and Nice respectively,
|
|
// so we exclude them to avoid double-counting (Linux kernel accounting)
|
|
idleDelta := cur.Idle - s.lastCPUTimes.Idle
|
|
busyDelta := (cur.User - s.lastCPUTimes.User) +
|
|
(cur.System - s.lastCPUTimes.System) +
|
|
(cur.Nice - s.lastCPUTimes.Nice) +
|
|
(cur.Iowait - s.lastCPUTimes.Iowait) +
|
|
(cur.Irq - s.lastCPUTimes.Irq) +
|
|
(cur.Softirq - s.lastCPUTimes.Softirq) +
|
|
(cur.Steal - s.lastCPUTimes.Steal)
|
|
|
|
totalDelta := busyDelta + idleDelta
|
|
|
|
// Update last sample for next time
|
|
s.lastCPUTimes = cur
|
|
|
|
// Guard against division by zero or negative deltas (e.g., counter resets)
|
|
if totalDelta <= 0 {
|
|
return s.emaCPU, nil
|
|
}
|
|
|
|
raw := 100.0 * (busyDelta / totalDelta)
|
|
if raw < 0 {
|
|
raw = 0
|
|
}
|
|
if raw > 100 {
|
|
raw = 100
|
|
}
|
|
|
|
// Exponential moving average to smooth spikes
|
|
const alpha = 0.3 // smoothing factor (0<alpha<=1). Higher = more responsive, lower = smoother
|
|
if s.emaCPU == 0 {
|
|
// Initialize EMA with the first real reading to avoid long warm-up from zero
|
|
s.emaCPU = raw
|
|
} else {
|
|
s.emaCPU = alpha*raw + (1-alpha)*s.emaCPU
|
|
}
|
|
|
|
return s.emaCPU, nil
|
|
}
|
|
|
|
const (
|
|
maxXrayArchiveBytes = 200 << 20
|
|
maxXrayBinaryBytes = 200 << 20
|
|
// maxXrayDigestBytes caps the .dgst checksum sidecar read; it is a few
|
|
// hundred bytes in practice.
|
|
maxXrayDigestBytes = 64 << 10
|
|
)
|
|
|
|
func (s *ServerService) GetXrayVersions() ([]string, error) {
|
|
const (
|
|
XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
|
|
bufferSize = 8192
|
|
)
|
|
|
|
req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, XrayURL, nil)
|
|
if reqErr != nil {
|
|
return nil, reqErr
|
|
}
|
|
resp, err := s.settingService.NewProxiedHTTPClient(10 * time.Second).Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// Check HTTP status code - GitHub API returns object instead of array on error
|
|
if resp.StatusCode != http.StatusOK {
|
|
bodyBytes, _ := io.ReadAll(resp.Body)
|
|
var errorResponse struct {
|
|
Message string `json:"message"`
|
|
}
|
|
if json.Unmarshal(bodyBytes, &errorResponse) == nil && errorResponse.Message != "" {
|
|
return nil, fmt.Errorf("GitHub API error: %s", errorResponse.Message)
|
|
}
|
|
return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
|
|
}
|
|
|
|
buffer := bytes.NewBuffer(make([]byte, bufferSize))
|
|
buffer.Reset()
|
|
if _, err := buffer.ReadFrom(resp.Body); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var releases []Release
|
|
if err := json.Unmarshal(buffer.Bytes(), &releases); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var versions []string
|
|
for _, release := range releases {
|
|
tagVersion := strings.TrimPrefix(release.TagName, "v")
|
|
tagParts := strings.Split(tagVersion, ".")
|
|
if len(tagParts) != 3 {
|
|
continue
|
|
}
|
|
|
|
major, err1 := strconv.Atoi(tagParts[0])
|
|
minor, err2 := strconv.Atoi(tagParts[1])
|
|
patch, err3 := strconv.Atoi(tagParts[2])
|
|
if err1 != nil || err2 != nil || err3 != nil {
|
|
continue
|
|
}
|
|
|
|
if major > 26 || (major == 26 && minor > 6) || (major == 26 && minor == 6 && patch >= 27) {
|
|
versions = append(versions, release.TagName)
|
|
}
|
|
}
|
|
return versions, nil
|
|
}
|
|
|
|
func (s *ServerService) StopXrayService() error {
|
|
err := s.xrayService.StopXray()
|
|
if err != nil {
|
|
logger.Error("stop xray failed:", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *ServerService) RestartXrayService() error {
|
|
err := s.xrayService.RestartXray(true)
|
|
if err != nil {
|
|
logger.Error("start xray failed:", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *ServerService) downloadXRay(version string) (string, error) {
|
|
osName := runtime.GOOS
|
|
arch := runtime.GOARCH
|
|
|
|
switch osName {
|
|
case "darwin":
|
|
osName = "macos"
|
|
case "windows":
|
|
osName = "windows"
|
|
}
|
|
|
|
switch arch {
|
|
case "amd64":
|
|
arch = "64"
|
|
case "arm64":
|
|
arch = "arm64-v8a"
|
|
case "armv7":
|
|
arch = "arm32-v7a"
|
|
case "armv6":
|
|
arch = "arm32-v6"
|
|
case "armv5":
|
|
arch = "arm32-v5"
|
|
case "386":
|
|
arch = "32"
|
|
case "s390x":
|
|
arch = "s390x"
|
|
}
|
|
|
|
fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
|
|
url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
|
|
client := s.settingService.NewProxiedHTTPClient(60 * time.Second)
|
|
req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
|
|
if reqErr != nil {
|
|
return "", reqErr
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("download xray: unexpected HTTP %d", resp.StatusCode)
|
|
}
|
|
if resp.ContentLength > maxXrayArchiveBytes {
|
|
return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
|
|
}
|
|
|
|
file, err := os.CreateTemp("", "xray-*.zip")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
path := file.Name()
|
|
ok := false
|
|
defer func() {
|
|
_ = file.Close()
|
|
if !ok {
|
|
_ = os.Remove(path)
|
|
}
|
|
}()
|
|
|
|
n, err := io.Copy(file, io.LimitReader(resp.Body, maxXrayArchiveBytes+1))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if n > maxXrayArchiveBytes {
|
|
return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
|
|
}
|
|
|
|
// Verify the archive against the SHA2-256 published in the release's .dgst
|
|
// sidecar before installing it. TLS protects the transport, not the artifact;
|
|
// a corrupted or tampered asset must not be installed and run as xray.
|
|
want, err := s.fetchXrayDigestSHA256(client, url+".dgst")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return "", err
|
|
}
|
|
hasher := sha256.New()
|
|
if _, err := io.Copy(hasher, file); err != nil {
|
|
return "", err
|
|
}
|
|
if got := hex.EncodeToString(hasher.Sum(nil)); !strings.EqualFold(got, want) {
|
|
// User-facing warning: the archive's SHA-256 does not match the official
|
|
// release checksum, so the download is corrupted or has been tampered
|
|
// with. Abort the install so a bad binary is never run, and tell the user
|
|
// to retry/re-download rather than proceed with a mismatched image.
|
|
return "", fmt.Errorf("Xray update aborted: the downloaded archive does not match the official SHA-256 checksum, so the image is corrupted or differs from the official release. Please exit and re-download the official image, then try again (expected %s, got %s)", want, got)
|
|
}
|
|
|
|
ok = true
|
|
return path, nil
|
|
}
|
|
|
|
// fetchXrayDigestSHA256 downloads the .dgst sidecar XTLS publishes next to each
|
|
// release asset and returns the SHA2-256 hex digest it lists.
|
|
func (s *ServerService) fetchXrayDigestSHA256(client *http.Client, dgstURL string) (string, error) {
|
|
req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, dgstURL, nil)
|
|
if reqErr != nil {
|
|
return "", fmt.Errorf("download xray checksum: %w", reqErr)
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "", fmt.Errorf("download xray checksum: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("download xray checksum: unexpected HTTP %d", resp.StatusCode)
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxXrayDigestBytes))
|
|
if err != nil {
|
|
return "", fmt.Errorf("download xray checksum: %w", err)
|
|
}
|
|
return parseXrayDigestSHA256(raw)
|
|
}
|
|
|
|
// parseXrayDigestSHA256 extracts the lowercase SHA2-256 hex from an XTLS .dgst
|
|
// file, whose lines are "ALGO= <hex>" (the relevant one being "SHA2-256= ...").
|
|
func parseXrayDigestSHA256(dgst []byte) (string, error) {
|
|
for line := range strings.SplitSeq(string(dgst), "\n") {
|
|
rest, ok := strings.CutPrefix(strings.TrimSpace(line), "SHA2-256=")
|
|
if !ok {
|
|
continue
|
|
}
|
|
h := strings.ToLower(strings.TrimSpace(rest))
|
|
if len(h) != 64 {
|
|
return "", fmt.Errorf("xray checksum: malformed SHA2-256 entry in digest")
|
|
}
|
|
return h, nil
|
|
}
|
|
return "", fmt.Errorf("xray checksum: no SHA2-256 entry in digest")
|
|
}
|
|
|
|
func (s *ServerService) UpdateXray(version string) error {
|
|
versions, err := s.GetXrayVersions()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !slices.Contains(versions, version) {
|
|
return fmt.Errorf("xray version %q is not in the fetched release list", version)
|
|
}
|
|
|
|
// 1. Stop xray before doing anything
|
|
if err := s.StopXrayService(); err != nil {
|
|
logger.Warning("failed to stop xray before update:", err)
|
|
}
|
|
|
|
// 2. Download the zip
|
|
zipFileName, err := s.downloadXRay(version)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(zipFileName)
|
|
|
|
zipFile, err := os.Open(zipFileName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer zipFile.Close()
|
|
|
|
stat, err := zipFile.Stat()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
reader, err := zip.NewReader(zipFile, stat.Size())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 3. Helper to extract files
|
|
copyZipFile := func(zipName string, fileName string) error {
|
|
zipFile, err := reader.Open(zipName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer zipFile.Close()
|
|
if err := os.MkdirAll(filepath.Dir(fileName), 0o755); err != nil {
|
|
return err
|
|
}
|
|
tmpFile, err := os.CreateTemp(filepath.Dir(fileName), ".xray-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tmpPath := tmpFile.Name()
|
|
ok := false
|
|
defer func() {
|
|
_ = tmpFile.Close()
|
|
if !ok {
|
|
_ = os.Remove(tmpPath)
|
|
}
|
|
}()
|
|
n, err := io.Copy(tmpFile, io.LimitReader(zipFile, maxXrayBinaryBytes+1))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n > maxXrayBinaryBytes {
|
|
return fmt.Errorf("xray binary exceeds %d bytes", maxXrayBinaryBytes)
|
|
}
|
|
if err := tmpFile.Chmod(0o755); err != nil {
|
|
return err
|
|
}
|
|
if err := tmpFile.Close(); err != nil {
|
|
return err
|
|
}
|
|
if runtime.GOOS == "windows" {
|
|
_ = os.Remove(fileName)
|
|
}
|
|
if err := os.Rename(tmpPath, fileName); err != nil {
|
|
return err
|
|
}
|
|
ok = true
|
|
return nil
|
|
}
|
|
|
|
// 4. Extract correct binary
|
|
if runtime.GOOS == "windows" {
|
|
targetBinary := filepath.Join(config.GetBinFolderPath(), "xray-windows-amd64.exe")
|
|
err = copyZipFile("xray.exe", targetBinary)
|
|
} else {
|
|
err = copyZipFile("xray", xray.GetBinaryPath())
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 5. Restart xray
|
|
if err := s.xrayService.RestartXray(true); err != nil {
|
|
logger.Error("start xray failed:", err)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
|
|
c, _ := strconv.Atoi(count)
|
|
var lines []string
|
|
|
|
if syslog == "true" {
|
|
// Check if running on Windows - journalctl is not available
|
|
if runtime.GOOS == "windows" {
|
|
return []string{"Syslog is not supported on Windows. Please use application logs instead by unchecking the 'Syslog' option."}
|
|
}
|
|
|
|
// Validate and sanitize count parameter
|
|
countInt, err := strconv.Atoi(count)
|
|
if err != nil || countInt < 1 || countInt > 10000 {
|
|
return []string{"Invalid count parameter - must be a number between 1 and 10000"}
|
|
}
|
|
|
|
// Validate level parameter - only allow valid syslog levels
|
|
validLevels := map[string]bool{
|
|
"0": true, "emerg": true,
|
|
"1": true, "alert": true,
|
|
"2": true, "crit": true,
|
|
"3": true, "err": true,
|
|
"4": true, "warning": true,
|
|
"5": true, "notice": true,
|
|
"6": true, "info": true,
|
|
"7": true, "debug": true,
|
|
}
|
|
if !validLevels[level] {
|
|
return []string{"Invalid level parameter - must be a valid syslog level"}
|
|
}
|
|
|
|
// Use hardcoded command with validated parameters
|
|
cmd := exec.CommandContext(context.Background(), "journalctl", "-u", "x-ui", "--no-pager", "-n", strconv.Itoa(countInt), "-p", level)
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err = cmd.Run()
|
|
if err != nil {
|
|
return []string{"Failed to run journalctl command! Make sure systemd is available and x-ui service is registered."}
|
|
}
|
|
lines = strings.Split(out.String(), "\n")
|
|
} else {
|
|
lines = logger.GetLogs(c, level)
|
|
}
|
|
|
|
return lines
|
|
}
|
|
|
|
// parseAccessLogFields extracts the structured fields from one Xray access-log
|
|
// line. Lines are attacker-influenced (a client's requested destination lands in
|
|
// the log verbatim) and may be truncated, so every positional lookup is length
|
|
// guarded: a malformed line yields a partial entry rather than panicking.
|
|
func parseAccessLogFields(line string) LogEntry {
|
|
var entry LogEntry
|
|
parts := strings.Fields(line)
|
|
|
|
for i, part := range parts {
|
|
|
|
if i == 0 && len(parts) > 1 {
|
|
dateTime, err := time.ParseInLocation("2006/01/02 15:04:05.999999", parts[0]+" "+parts[1], time.Local)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
entry.DateTime = dateTime.UTC()
|
|
}
|
|
|
|
if part == "from" && i+1 < len(parts) {
|
|
entry.FromAddress = strings.TrimLeft(parts[i+1], "/")
|
|
} else if part == "accepted" && i+1 < len(parts) {
|
|
entry.ToAddress = strings.TrimLeft(parts[i+1], "/")
|
|
} else if strings.HasPrefix(part, "[") {
|
|
entry.Inbound = part[1:]
|
|
} else if strings.HasSuffix(part, "]") {
|
|
entry.Outbound = part[:len(part)-1]
|
|
} else if part == "email:" && i+1 < len(parts) {
|
|
entry.Email = parts[i+1]
|
|
}
|
|
}
|
|
|
|
return entry
|
|
}
|
|
|
|
func (s *ServerService) GetXrayLogs(
|
|
count string,
|
|
filter string,
|
|
showDirect string,
|
|
showBlocked string,
|
|
showProxy string,
|
|
freedoms []string,
|
|
blackholes []string,
|
|
) []LogEntry {
|
|
const (
|
|
Direct = iota
|
|
Blocked
|
|
Proxied
|
|
)
|
|
|
|
countInt, _ := strconv.Atoi(count)
|
|
var entries []LogEntry
|
|
|
|
pathToAccessLog, err := xray.GetAccessLogPath()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
file, err := os.Open(pathToAccessLog)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
for scanner.Scan() {
|
|
line := strings.TrimSpace(scanner.Text())
|
|
|
|
if line == "" || strings.Contains(line, "api -> api") {
|
|
// skipping empty lines and api calls
|
|
continue
|
|
}
|
|
|
|
if filter != "" && !strings.Contains(line, filter) {
|
|
// applying filter if it's not empty
|
|
continue
|
|
}
|
|
|
|
entry := parseAccessLogFields(line)
|
|
|
|
if logEntryContains(line, freedoms) {
|
|
if showDirect == "false" {
|
|
continue
|
|
}
|
|
entry.Event = Direct
|
|
} else if logEntryContains(line, blackholes) {
|
|
if showBlocked == "false" {
|
|
continue
|
|
}
|
|
entry.Event = Blocked
|
|
} else {
|
|
if showProxy == "false" {
|
|
continue
|
|
}
|
|
entry.Event = Proxied
|
|
}
|
|
|
|
entries = append(entries, entry)
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return nil
|
|
}
|
|
|
|
if len(entries) > countInt {
|
|
entries = entries[len(entries)-countInt:]
|
|
}
|
|
|
|
return entries
|
|
}
|
|
|
|
// isVirtualInterface returns true for loopback and virtual/tunnel interfaces
|
|
// that should be excluded from network traffic statistics.
|
|
func isVirtualInterface(name string) bool {
|
|
// Exact matches
|
|
if name == "lo" || name == "lo0" {
|
|
return true
|
|
}
|
|
// Prefix matches for virtual/tunnel interfaces
|
|
virtualPrefixes := []string{
|
|
"loopback",
|
|
"docker",
|
|
"br-",
|
|
"veth",
|
|
"virbr",
|
|
"tun",
|
|
"tap",
|
|
"wg",
|
|
"tailscale",
|
|
"zt",
|
|
}
|
|
for _, prefix := range virtualPrefixes {
|
|
if strings.HasPrefix(name, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func logEntryContains(line string, suffixes []string) bool {
|
|
for _, sfx := range suffixes {
|
|
if strings.Contains(line, sfx+"]") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (s *ServerService) GetConfigJson() (any, error) {
|
|
config, err := s.xrayService.GetXrayConfig()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
contents, err := json.MarshalIndent(config, "", " ")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var jsonData any
|
|
err = json.Unmarshal(contents, &jsonData)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return jsonData, nil
|
|
}
|
|
|
|
func (s *ServerService) GetDb() ([]byte, error) {
|
|
if database.IsPostgres() {
|
|
return s.exportPostgresDB()
|
|
}
|
|
// Update by manually trigger a checkpoint operation
|
|
err := database.Checkpoint()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Open the file for reading
|
|
file, err := os.Open(config.GetDBPath())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
|
|
// Read the file contents
|
|
fileContents, err := io.ReadAll(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return fileContents, nil
|
|
}
|
|
|
|
// BackupFilename returns the filename for a database backup, named after the
|
|
// panel's address so a downloaded or Telegram-sent backup identifies the server
|
|
// it came from, followed by the current date and time (_YYYY-MM-DD_HHMMSS) so
|
|
// files accumulated in Telegram chat history group by server then sort
|
|
// chronologically and same-day backups stay distinct. requestHost is the
|
|
// browser's address: the getDb handler passes c.Request.Host so a panel download
|
|
// is named after whatever address the user reached the panel with, no Listen
|
|
// Domain needed. The Telegram bot has no request and passes "", falling back to
|
|
// the configured Listen Domain (webDomain) and then the public IP. The extension
|
|
// is .dump on PostgreSQL and .db on SQLite; the base falls back to "x-ui" when
|
|
// no address is known.
|
|
func (s *ServerService) BackupFilename(requestHost string) string {
|
|
ext := ".db"
|
|
if database.IsPostgres() {
|
|
ext = ".dump"
|
|
}
|
|
return s.backupHost(requestHost) + backupDateSuffix(time.Now()) + ext
|
|
}
|
|
|
|
// backupDateSuffix returns the _YYYY-MM-DD_HHMMSS chronological suffix appended
|
|
// after the host in backup filenames. Uses server-local time for consistency
|
|
// with the timestamp printed in the Telegram backup message body.
|
|
func backupDateSuffix(now time.Time) string {
|
|
return "_" + now.Format("2006-01-02_150405")
|
|
}
|
|
|
|
// backupHost picks the address used to name backup files: the browser's request
|
|
// host (port stripped) when available, otherwise the configured Listen Domain
|
|
// (webDomain) and then the resolved public IP (IPv4 before IPv6), reduced to safe
|
|
// filename characters. The public IP is resolved directly rather than read from
|
|
// LastStatus so callers whose ServerService never runs the status ticker —
|
|
// notably the Telegram bot — still get a real address instead of the "x-ui"
|
|
// fallback.
|
|
func (s *ServerService) backupHost(requestHost string) string {
|
|
host := extractHostname(strings.TrimSpace(requestHost))
|
|
if host == "" {
|
|
if domain, err := s.settingService.GetWebDomain(); err == nil {
|
|
host = strings.TrimSpace(domain)
|
|
}
|
|
}
|
|
if host == "" {
|
|
s.resolvePublicIPs()
|
|
if ip := s.cachedIPv4; ip != "" && ip != "N/A" {
|
|
host = ip
|
|
} else if ip := s.cachedIPv6; ip != "" && ip != "N/A" {
|
|
host = ip
|
|
}
|
|
}
|
|
return sanitizeBackupHost(host)
|
|
}
|
|
|
|
// sanitizeBackupHost reduces a host to characters safe in a download filename
|
|
// (the getDb handler enforces ^[a-zA-Z0-9_\-.]+$). IPv6 brackets are stripped
|
|
// and any other character — such as the colons in an IPv6 address — becomes a
|
|
// hyphen. Returns "x-ui" when nothing usable remains.
|
|
func sanitizeBackupHost(host string) string {
|
|
host = strings.Trim(host, "[]")
|
|
var b strings.Builder
|
|
for _, r := range host {
|
|
switch {
|
|
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_':
|
|
b.WriteRune(r)
|
|
default:
|
|
b.WriteRune('-')
|
|
}
|
|
}
|
|
out := strings.Trim(b.String(), ".-")
|
|
if out == "" {
|
|
return "x-ui"
|
|
}
|
|
return out
|
|
}
|
|
|
|
// GetMigration produces a cross-engine migration file plus its filename: on a
|
|
// SQLite panel it returns a portable .dump (SQL text), and on a PostgreSQL panel
|
|
// it returns a .db SQLite database built from the live data. Either output can
|
|
// then seed a panel running on the other backend.
|
|
func (s *ServerService) GetMigration() ([]byte, string, error) {
|
|
if database.IsPostgres() {
|
|
tmp, err := os.CreateTemp("", "x-ui-migration-*.db")
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
tmpPath := tmp.Name()
|
|
tmp.Close()
|
|
defer os.Remove(tmpPath)
|
|
|
|
if err := database.ExportPostgresToSQLite(config.GetDBDSN(), tmpPath); err != nil {
|
|
return nil, "", err
|
|
}
|
|
data, err := os.ReadFile(tmpPath)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return data, "x-ui.db", nil
|
|
}
|
|
|
|
// SQLite panel: checkpoint so the .db reflects the latest writes, then dump.
|
|
if err := database.Checkpoint(); err != nil {
|
|
return nil, "", err
|
|
}
|
|
data, err := database.DumpSQLiteToBytes(config.GetDBPath())
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return data, "x-ui.dump", nil
|
|
}
|
|
|
|
func (s *ServerService) ImportDB(file multipart.File) error {
|
|
if database.IsPostgres() {
|
|
return s.importPostgresDB(file)
|
|
}
|
|
kind, err := sniffUploadKind(file)
|
|
if err != nil {
|
|
return common.NewErrorf("Error reading uploaded file: %v", err)
|
|
}
|
|
switch kind {
|
|
case importKindSQLiteDB, importKindSQLiteDump:
|
|
case importKindPgDump:
|
|
return common.NewError("This file is a PostgreSQL backup; it can only be restored on a panel running PostgreSQL")
|
|
default:
|
|
return common.NewError("Invalid file: expected a SQLite database (.db) from Back Up or a SQLite migration dump (.dump)")
|
|
}
|
|
|
|
tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
|
|
|
|
if _, err := os.Stat(tempPath); err == nil {
|
|
if errRemove := os.Remove(tempPath); errRemove != nil {
|
|
return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
|
|
}
|
|
}
|
|
defer func() {
|
|
if _, err := os.Stat(tempPath); err == nil {
|
|
if rerr := os.Remove(tempPath); rerr != nil {
|
|
logger.Warningf("Warning: failed to remove temp file: %v", rerr)
|
|
}
|
|
}
|
|
}()
|
|
|
|
if err := stageSQLiteUpload(file, kind, tempPath); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = database.ValidateSQLiteDB(tempPath); err != nil {
|
|
return common.NewErrorf("Invalid or corrupt db file: %v", err)
|
|
}
|
|
if err = database.PrepareSQLiteForMigration(tempPath); err != nil {
|
|
return common.NewErrorf("This file cannot be imported: %v", err)
|
|
}
|
|
|
|
xrayStopped := true
|
|
defer func() {
|
|
if xrayStopped {
|
|
if errR := s.RestartXrayService(); errR != nil {
|
|
logger.Warningf("Failed to restart Xray after DB import error: %v", errR)
|
|
}
|
|
}
|
|
}()
|
|
if errStop := s.StopXrayService(); errStop != nil {
|
|
logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
|
|
}
|
|
|
|
if errClose := database.CloseDB(); errClose != nil {
|
|
logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
|
|
}
|
|
|
|
// Registered after the xray-restart defer so it runs first (LIFO): every
|
|
// error return below leaves a database file at the configured path, and the
|
|
// restart needs an open pool to build the xray config from it.
|
|
dbReopened := false
|
|
defer func() {
|
|
if dbReopened {
|
|
return
|
|
}
|
|
if errReopen := database.InitDB(config.GetDBPath()); errReopen != nil {
|
|
logger.Warningf("Failed to reopen the database after import error: %v", errReopen)
|
|
}
|
|
}()
|
|
|
|
// Backup the current database for fallback
|
|
fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
|
|
|
|
// Remove the existing fallback file (if any)
|
|
if _, err := os.Stat(fallbackPath); err == nil {
|
|
if errRemove := os.Remove(fallbackPath); errRemove != nil {
|
|
return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
|
|
}
|
|
}
|
|
|
|
// Move the current database to the fallback location
|
|
if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
|
|
return common.NewErrorf("Error backing up current db file: %v", err)
|
|
}
|
|
|
|
// Move temp to DB path
|
|
if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
|
|
// Restore from fallback
|
|
if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
|
|
return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
|
|
}
|
|
return common.NewErrorf("Error moving db file: %v", err)
|
|
}
|
|
|
|
// Open & migrate new DB
|
|
if err = database.InitDB(config.GetDBPath()); err != nil {
|
|
// A failed InitDB still holds the imported file open; close before the
|
|
// rename or Windows refuses to replace it.
|
|
if errClose := database.CloseDB(); errClose != nil {
|
|
logger.Warningf("Failed to close the imported DB before restoring fallback: %v", errClose)
|
|
}
|
|
if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
|
|
return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
|
|
}
|
|
return common.NewErrorf("Error migrating db: %v", err)
|
|
}
|
|
dbReopened = true
|
|
|
|
s.inboundService.MigrateDB()
|
|
|
|
xrayStopped = false
|
|
if err = s.RestartXrayService(); err != nil {
|
|
return common.NewErrorf("Imported DB but failed to start Xray: %v; the previous database was kept at %s", err, fallbackPath)
|
|
}
|
|
|
|
if _, err := os.Stat(fallbackPath); err == nil {
|
|
if rerr := os.Remove(fallbackPath); rerr != nil {
|
|
logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// pgConnEnv turns the configured PostgreSQL DSN into the PG* environment used by
|
|
// pg_dump/pg_restore, keeping the password out of the process argument list.
|
|
func pgConnEnv(dsn string) (env []string, dbname string, err error) {
|
|
u, err := url.Parse(strings.TrimSpace(dsn))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if u.Scheme != "postgres" && u.Scheme != "postgresql" {
|
|
return nil, "", common.NewErrorf("unsupported DSN scheme %q", u.Scheme)
|
|
}
|
|
dbname = strings.TrimPrefix(u.Path, "/")
|
|
if dbname == "" {
|
|
return nil, "", common.NewError("PostgreSQL DSN is missing a database name")
|
|
}
|
|
host := u.Hostname()
|
|
if host == "" {
|
|
host = "127.0.0.1"
|
|
}
|
|
port := u.Port()
|
|
if port == "" {
|
|
port = "5432"
|
|
}
|
|
env = append(os.Environ(), "PGHOST="+host, "PGPORT="+port, "PGDATABASE="+dbname)
|
|
if user := u.User.Username(); user != "" {
|
|
env = append(env, "PGUSER="+user)
|
|
}
|
|
if pass, ok := u.User.Password(); ok {
|
|
env = append(env, "PGPASSWORD="+pass)
|
|
}
|
|
if sslmode := u.Query().Get("sslmode"); sslmode != "" {
|
|
env = append(env, "PGSSLMODE="+sslmode)
|
|
}
|
|
return env, dbname, nil
|
|
}
|
|
|
|
func (s *ServerService) exportPostgresDB() ([]byte, error) {
|
|
bin, err := exec.LookPath("pg_dump")
|
|
if err != nil {
|
|
return nil, common.NewError("pg_dump not found on the server; install the postgresql-client package to back up a PostgreSQL database")
|
|
}
|
|
env, dbname, err := pgConnEnv(config.GetDBDSN())
|
|
if err != nil {
|
|
return nil, common.NewErrorf("invalid PostgreSQL DSN: %v", err)
|
|
}
|
|
cmd := exec.CommandContext(context.Background(), bin, "--format=custom", "--no-owner", "--no-privileges", "--dbname", dbname)
|
|
cmd.Env = env
|
|
var out, stderr bytes.Buffer
|
|
cmd.Stdout = &out
|
|
cmd.Stderr = &stderr
|
|
if err := cmd.Run(); err != nil {
|
|
return nil, common.NewErrorf("pg_dump failed: %v: %s", err, strings.TrimSpace(stderr.String()))
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|
|
|
|
var (
|
|
pgUnsupportedDumpVersionPattern = regexp.MustCompile(`unsupported version \((\d+\.\d+)\) in file header`)
|
|
pgToolVersionPattern = regexp.MustCompile(`\d+(?:\.\d+)+`)
|
|
)
|
|
|
|
var pgArchiveVersionIntroducedIn = map[string]int{
|
|
"1.15": 16,
|
|
"1.16": 17,
|
|
}
|
|
|
|
// checkPgRestoreCanRead probes the dump with pg_restore --list (reads only the
|
|
// TOC, no database connection) so an unreadable file fails before Xray is stopped.
|
|
func checkPgRestoreCanRead(bin, dumpPath string) error {
|
|
cmd := exec.CommandContext(context.Background(), bin, "--list", dumpPath)
|
|
cmd.Stdout = io.Discard
|
|
var stderr bytes.Buffer
|
|
cmd.Stderr = &stderr
|
|
if cmd.Run() == nil {
|
|
return nil
|
|
}
|
|
return pgRestoreReadFailureError(strings.TrimSpace(stderr.String()), pgRestoreVersion(bin))
|
|
}
|
|
|
|
func pgRestoreReadFailureError(probeOutput, localVersion string) error {
|
|
m := pgUnsupportedDumpVersionPattern.FindStringSubmatch(probeOutput)
|
|
if m == nil {
|
|
return common.NewErrorf("pg_restore cannot read this dump file: %s", probeOutput)
|
|
}
|
|
if localVersion == "" {
|
|
localVersion = "unknown"
|
|
}
|
|
if major, known := pgArchiveVersionIntroducedIn[m[1]]; known {
|
|
return common.NewErrorf("This backup was created by pg_dump from PostgreSQL %d or newer, but the server's pg_restore is version %s and cannot read it; run 'x-ui pgclient %d' on the server (or upgrade the postgresql-client package to version %d or newer), then retry the import", major, localVersion, major, major)
|
|
}
|
|
return common.NewErrorf("This backup was created by a newer pg_dump than the server's pg_restore (version %s) can read; upgrade the postgresql-client package and retry the import", localVersion)
|
|
}
|
|
|
|
func pgRestoreVersion(bin string) string {
|
|
out, err := exec.CommandContext(context.Background(), bin, "--version").Output()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return parsePgToolVersion(string(out))
|
|
}
|
|
|
|
func parsePgToolVersion(versionOutput string) string {
|
|
return pgToolVersionPattern.FindString(versionOutput)
|
|
}
|
|
|
|
const (
|
|
importKindUnknown = iota
|
|
importKindPgDump
|
|
importKindSQLiteDB
|
|
importKindSQLiteDump
|
|
)
|
|
|
|
// sniffImportKind classifies an uploaded restore file by its leading bytes:
|
|
// a pg_dump custom archive, a raw SQLite database, or a SQLite SQL text dump.
|
|
func sniffImportKind(header []byte) int {
|
|
if bytes.HasPrefix(header, []byte("PGDMP")) {
|
|
return importKindPgDump
|
|
}
|
|
if bytes.HasPrefix(header, []byte("SQLite format 3\x00")) {
|
|
return importKindSQLiteDB
|
|
}
|
|
text := bytes.TrimLeft(bytes.TrimPrefix(header, []byte("\xef\xbb\xbf")), " \t\r\n")
|
|
if bytes.HasPrefix(text, []byte("PRAGMA")) || bytes.HasPrefix(text, []byte("BEGIN TRANSACTION")) {
|
|
return importKindSQLiteDump
|
|
}
|
|
return importKindUnknown
|
|
}
|
|
|
|
func sniffUploadKind(file multipart.File) (int, error) {
|
|
header := make([]byte, 64)
|
|
n, err := file.ReadAt(header, 0)
|
|
if err != nil && !errors.Is(err, io.EOF) {
|
|
return importKindUnknown, err
|
|
}
|
|
if _, err := file.Seek(0, 0); err != nil {
|
|
return importKindUnknown, err
|
|
}
|
|
return sniffImportKind(header[:n]), nil
|
|
}
|
|
|
|
func (s *ServerService) importPostgresDB(file multipart.File) error {
|
|
kind, err := sniffUploadKind(file)
|
|
if err != nil {
|
|
return common.NewErrorf("Error reading uploaded file: %v", err)
|
|
}
|
|
switch kind {
|
|
case importKindPgDump:
|
|
return s.restorePostgresDump(file)
|
|
case importKindSQLiteDB:
|
|
return s.migrateSQLiteIntoPostgres(file, false)
|
|
case importKindSQLiteDump:
|
|
return s.migrateSQLiteIntoPostgres(file, true)
|
|
default:
|
|
return common.NewError("Invalid file: expected a PostgreSQL custom-format dump (.dump) from this panel's Back Up, a SQLite database (.db), or a SQLite migration dump")
|
|
}
|
|
}
|
|
|
|
func (s *ServerService) restorePostgresDump(file multipart.File) error {
|
|
bin, err := exec.LookPath("pg_restore")
|
|
if err != nil {
|
|
return common.NewError("pg_restore not found on the server; install the postgresql-client package to restore a PostgreSQL database")
|
|
}
|
|
env, dbname, err := pgConnEnv(config.GetDBDSN())
|
|
if err != nil {
|
|
return common.NewErrorf("invalid PostgreSQL DSN: %v", err)
|
|
}
|
|
|
|
tempFile, err := os.CreateTemp("", "x-ui-pg-restore-*.dump")
|
|
if err != nil {
|
|
return common.NewErrorf("Error creating temporary dump file: %v", err)
|
|
}
|
|
tempPath := tempFile.Name()
|
|
defer os.Remove(tempPath)
|
|
if _, err := io.Copy(tempFile, file); err != nil {
|
|
tempFile.Close()
|
|
return common.NewErrorf("Error saving dump: %v", err)
|
|
}
|
|
if err := tempFile.Close(); err != nil {
|
|
return common.NewErrorf("Error closing temporary dump file: %v", err)
|
|
}
|
|
|
|
if err := checkPgRestoreCanRead(bin, tempPath); err != nil {
|
|
return err
|
|
}
|
|
|
|
xrayStopped := true
|
|
defer func() {
|
|
if xrayStopped {
|
|
if errR := s.RestartXrayService(); errR != nil {
|
|
logger.Warningf("Failed to restart Xray after DB restore error: %v", errR)
|
|
}
|
|
}
|
|
}()
|
|
if errStop := s.StopXrayService(); errStop != nil {
|
|
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
|
|
}
|
|
|
|
if errClose := database.CloseDB(); errClose != nil {
|
|
logger.Warningf("Failed to close existing DB before restore: %v", errClose)
|
|
}
|
|
|
|
cmd := exec.CommandContext(context.Background(), bin,
|
|
"--clean", "--if-exists", "--no-owner", "--no-privileges",
|
|
"--single-transaction", "--dbname", dbname, tempPath,
|
|
)
|
|
cmd.Env = env
|
|
var stderr bytes.Buffer
|
|
cmd.Stderr = &stderr
|
|
runErr := cmd.Run()
|
|
|
|
if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
|
|
return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
|
|
}
|
|
s.inboundService.MigrateDB()
|
|
|
|
if runErr != nil {
|
|
return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String()))
|
|
}
|
|
|
|
xrayStopped = false
|
|
if err := s.RestartXrayService(); err != nil {
|
|
return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump bool) error {
|
|
tempDir, err := os.MkdirTemp("", "x-ui-pg-migrate-*")
|
|
if err != nil {
|
|
return common.NewErrorf("Error creating temporary folder: %v", err)
|
|
}
|
|
defer os.RemoveAll(tempDir)
|
|
|
|
uploadPath := filepath.Join(tempDir, "upload.db")
|
|
if isSQLDump {
|
|
uploadPath = filepath.Join(tempDir, "upload.dump")
|
|
}
|
|
if err := saveUploadedFile(file, uploadPath); err != nil {
|
|
return common.NewErrorf("Error saving uploaded file: %v", err)
|
|
}
|
|
|
|
dbPath := uploadPath
|
|
if isSQLDump {
|
|
dbPath = filepath.Join(tempDir, "restored.db")
|
|
if err := database.RestoreSQLite(uploadPath, dbPath); err != nil {
|
|
return common.NewErrorf("Error rebuilding a SQLite database from the migration dump: %v", err)
|
|
}
|
|
}
|
|
if err := database.ValidateSQLiteDB(dbPath); err != nil {
|
|
return common.NewErrorf("Invalid or corrupt db file: %v", err)
|
|
}
|
|
if err := database.PrepareSQLiteForMigration(dbPath); err != nil {
|
|
return common.NewErrorf("This file cannot be imported: %v", err)
|
|
}
|
|
|
|
xrayStopped := true
|
|
defer func() {
|
|
if xrayStopped {
|
|
if errR := s.RestartXrayService(); errR != nil {
|
|
logger.Warningf("Failed to restart Xray after DB restore error: %v", errR)
|
|
}
|
|
}
|
|
}()
|
|
if errStop := s.StopXrayService(); errStop != nil {
|
|
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
|
|
}
|
|
|
|
if errClose := database.CloseDB(); errClose != nil {
|
|
logger.Warningf("Failed to close existing DB before restore: %v", errClose)
|
|
}
|
|
|
|
migrateErr := database.MigrateData(dbPath, config.GetDBDSN())
|
|
|
|
if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
|
|
return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
|
|
}
|
|
s.inboundService.MigrateDB()
|
|
|
|
if migrateErr != nil {
|
|
return common.NewErrorf("Importing the SQLite data into PostgreSQL failed: %v; the import runs in a single transaction, so the database was left unchanged", migrateErr)
|
|
}
|
|
|
|
xrayStopped = false
|
|
if err := s.RestartXrayService(); err != nil {
|
|
return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func saveUploadedFile(file multipart.File, dstPath string) error {
|
|
dst, err := os.Create(dstPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := io.Copy(dst, file); err != nil {
|
|
dst.Close()
|
|
return err
|
|
}
|
|
return dst.Close()
|
|
}
|
|
|
|
func stageSQLiteUpload(file multipart.File, kind int, tempPath string) error {
|
|
if kind == importKindSQLiteDump {
|
|
dumpPath := tempPath + ".dump"
|
|
defer os.Remove(dumpPath)
|
|
if err := saveUploadedFile(file, dumpPath); err != nil {
|
|
return common.NewErrorf("Error saving migration dump: %v", err)
|
|
}
|
|
if err := database.RestoreSQLite(dumpPath, tempPath); err != nil {
|
|
return common.NewErrorf("Error rebuilding a SQLite database from the migration dump: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
if err := saveUploadedFile(file, tempPath); err != nil {
|
|
return common.NewErrorf("Error saving db: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// IsValidGeofileName validates that the filename is safe for geofile operations.
|
|
// It checks for path traversal attempts and ensures the filename contains only safe characters.
|
|
func (s *ServerService) IsValidGeofileName(filename string) bool {
|
|
if filename == "" {
|
|
return false
|
|
}
|
|
|
|
// Check for path traversal attempts
|
|
if strings.Contains(filename, "..") {
|
|
return false
|
|
}
|
|
|
|
// Check for path separators (both forward and backward slash)
|
|
if strings.ContainsAny(filename, `/\`) {
|
|
return false
|
|
}
|
|
|
|
// Check for absolute path indicators
|
|
if filepath.IsAbs(filename) {
|
|
return false
|
|
}
|
|
|
|
// Additional security: only allow alphanumeric, dots, underscores, and hyphens
|
|
// This is stricter than the general filename regex
|
|
validGeofilePattern := `^[a-zA-Z0-9._-]+\.dat$`
|
|
matched, _ := regexp.MatchString(validGeofilePattern, filename)
|
|
return matched
|
|
}
|
|
|
|
func (s *ServerService) UpdateGeofile(fileName string) error {
|
|
type geofileEntry struct {
|
|
URL string
|
|
FileName string
|
|
}
|
|
geofileAllowlist := map[string]geofileEntry{
|
|
"geoip.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
|
|
"geosite.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
|
|
"geoip_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
|
|
"geosite_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
|
|
"geoip_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
|
|
"geosite_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
|
|
}
|
|
|
|
// Strict allowlist check to avoid writing uncontrolled files
|
|
if fileName != "" {
|
|
if _, ok := geofileAllowlist[fileName]; !ok {
|
|
return common.NewErrorf("Invalid geofile name: %q not in allowlist", fileName)
|
|
}
|
|
}
|
|
|
|
client := s.settingService.NewProxiedHTTPClient(0)
|
|
|
|
downloadFile := func(url, destPath string) error {
|
|
var req *http.Request
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return common.NewErrorf("Failed to create HTTP request for %s: %v", url, err)
|
|
}
|
|
|
|
var localFileModTime time.Time
|
|
if fileInfo, err := os.Stat(destPath); err == nil {
|
|
localFileModTime = fileInfo.ModTime()
|
|
if !localFileModTime.IsZero() {
|
|
req.Header.Set("If-Modified-Since", localFileModTime.UTC().Format(http.TimeFormat))
|
|
}
|
|
}
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// Parse Last-Modified header from server
|
|
var serverModTime time.Time
|
|
serverModTimeStr := resp.Header.Get("Last-Modified")
|
|
if serverModTimeStr != "" {
|
|
parsedTime, err := time.Parse(http.TimeFormat, serverModTimeStr)
|
|
if err != nil {
|
|
logger.Warningf("Failed to parse Last-Modified header for %s: %v", url, err)
|
|
} else {
|
|
serverModTime = parsedTime
|
|
}
|
|
}
|
|
|
|
// Function to update local file's modification time
|
|
updateFileModTime := func() {
|
|
if !serverModTime.IsZero() {
|
|
if err := os.Chtimes(destPath, serverModTime, serverModTime); err != nil {
|
|
logger.Warningf("Failed to update modification time for %s: %v", destPath, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle 304 Not Modified
|
|
if resp.StatusCode == http.StatusNotModified {
|
|
updateFileModTime()
|
|
return nil
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return common.NewErrorf("Failed to download Geofile from %s: received status code %d", url, resp.StatusCode)
|
|
}
|
|
|
|
file, err := os.Create(destPath)
|
|
if err != nil {
|
|
return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
|
|
}
|
|
defer file.Close()
|
|
|
|
_, err = io.Copy(file, resp.Body)
|
|
if err != nil {
|
|
return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
|
|
}
|
|
|
|
updateFileModTime()
|
|
return nil
|
|
}
|
|
|
|
var errorMessages []string
|
|
|
|
if fileName == "" {
|
|
// Download all geofiles
|
|
for _, entry := range geofileAllowlist {
|
|
destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
|
|
if err := downloadFile(entry.URL, destPath); err != nil {
|
|
errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
|
|
}
|
|
}
|
|
} else {
|
|
entry := geofileAllowlist[fileName]
|
|
destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
|
|
if err := downloadFile(entry.URL, destPath); err != nil {
|
|
errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
|
|
}
|
|
}
|
|
|
|
err := s.RestartXrayService()
|
|
if err != nil {
|
|
errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
|
|
}
|
|
|
|
if len(errorMessages) > 0 {
|
|
return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// parseXrayKeyPairOutput reads the two-line "Label: value" output that xray's
|
|
// key-generation subcommands (x25519, mldsa65, mlkem768) print and returns the
|
|
// two values. Short or label-less output yields an error instead of panicking
|
|
// on an out-of-range slice index, so a future xray version that changes the
|
|
// format degrades to a 500 with a message rather than a crash.
|
|
func parseXrayKeyPairOutput(output string) (string, string, error) {
|
|
lines := strings.Split(output, "\n")
|
|
if len(lines) < 2 {
|
|
return "", "", common.NewError("unexpected key generator output")
|
|
}
|
|
first := strings.Split(lines[0], ":")
|
|
second := strings.Split(lines[1], ":")
|
|
if len(first) < 2 || len(second) < 2 {
|
|
return "", "", common.NewError("unexpected key generator output")
|
|
}
|
|
return strings.TrimSpace(first[1]), strings.TrimSpace(second[1]), nil
|
|
}
|
|
|
|
func (s *ServerService) GetNewX25519Cert() (any, error) {
|
|
// Run the command
|
|
cmd := exec.CommandContext(context.Background(), xray.GetBinaryPath(), "x25519")
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
privateKey, publicKey, err := parseXrayKeyPairOutput(out.String())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
keyPair := map[string]any{
|
|
"privateKey": privateKey,
|
|
"publicKey": publicKey,
|
|
}
|
|
|
|
return keyPair, nil
|
|
}
|
|
|
|
func (s *ServerService) GetNewmldsa65() (any, error) {
|
|
// Run the command
|
|
cmd := exec.CommandContext(context.Background(), xray.GetBinaryPath(), "mldsa65")
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
seed, verify, err := parseXrayKeyPairOutput(out.String())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
keyPair := map[string]any{
|
|
"seed": seed,
|
|
"verify": verify,
|
|
}
|
|
|
|
return keyPair, nil
|
|
}
|
|
|
|
// GetCertHash parses a certificate (from a file path or inline PEM/DER content)
|
|
// and returns the hex-encoded SHA-256 over each certificate's raw DER — the
|
|
// value xray-core's pinnedPeerCertSha256 (pcs) expects. Lets the panel fill the
|
|
// pinned-cert field from the inbound's own certificate without the user
|
|
// computing the hash by hand.
|
|
func (s *ServerService) GetCertHash(certFile string, certContent string) ([]string, error) {
|
|
var certBytes []byte
|
|
if path := strings.TrimSpace(certFile); path != "" {
|
|
// Guard against path traversal: only hash certificate files the panel
|
|
// already references in its own configuration (an inbound's TLS
|
|
// certificateFile or the panel's own web cert). The path handed to
|
|
// os.ReadFile comes from that allow-list, never directly from the
|
|
// caller-supplied value.
|
|
known, ok := s.resolveKnownCertFile(path)
|
|
if !ok {
|
|
return nil, common.NewError("certificate file is not referenced by any inbound or panel setting")
|
|
}
|
|
b, err := os.ReadFile(known)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
certBytes = b
|
|
} else if strings.TrimSpace(certContent) != "" {
|
|
certBytes = []byte(certContent)
|
|
} else {
|
|
return nil, common.NewError("no certificate provided")
|
|
}
|
|
|
|
var certs []*x509.Certificate
|
|
if bytes.Contains(certBytes, []byte("BEGIN")) {
|
|
rest := certBytes
|
|
for {
|
|
block, remain := pem.Decode(rest)
|
|
if block == nil {
|
|
break
|
|
}
|
|
cert, err := x509.ParseCertificate(block.Bytes)
|
|
if err != nil {
|
|
return nil, common.NewError("unable to decode certificate: ", err)
|
|
}
|
|
certs = append(certs, cert)
|
|
rest = remain
|
|
}
|
|
} else {
|
|
parsed, err := x509.ParseCertificates(certBytes)
|
|
if err != nil {
|
|
return nil, common.NewError("unable to parse certificates: ", err)
|
|
}
|
|
certs = parsed
|
|
}
|
|
|
|
if len(certs) == 0 {
|
|
return nil, common.NewError("no certificates found")
|
|
}
|
|
|
|
hashes := make([]string, 0, len(certs))
|
|
for _, cert := range certs {
|
|
sum := sha256.Sum256(cert.Raw)
|
|
hashes = append(hashes, hex.EncodeToString(sum[:]))
|
|
}
|
|
return hashes, nil
|
|
}
|
|
|
|
// resolveKnownCertFile checks the caller-supplied certificate path against the
|
|
// set of certificate files the panel already references (inbound TLS configs
|
|
// plus the panel's own web cert) and, on a match, returns the path taken from
|
|
// that configuration — not the caller's value. This both confines reads to
|
|
// known certificates and breaks the user-input-to-filesystem taint flow.
|
|
func (s *ServerService) resolveKnownCertFile(certFile string) (string, bool) {
|
|
want := filepath.Clean(certFile)
|
|
for _, known := range s.knownCertFiles() {
|
|
if filepath.Clean(known) == want {
|
|
return known, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// knownCertFiles collects every certificate file path the panel legitimately
|
|
// references: the certificateFile of each inbound's TLS settings and the
|
|
// panel's own web TLS certificate.
|
|
func (s *ServerService) knownCertFiles() []string {
|
|
var files []string
|
|
if cert, err := s.settingService.GetCertFile(); err == nil {
|
|
if cert = strings.TrimSpace(cert); cert != "" {
|
|
files = append(files, cert)
|
|
}
|
|
}
|
|
if inbounds, err := s.inboundService.GetAllInbounds(); err == nil {
|
|
for _, inbound := range inbounds {
|
|
files = collectCertFiles(inbound.StreamSettings, files)
|
|
}
|
|
}
|
|
return files
|
|
}
|
|
|
|
// collectCertFiles walks a stream-settings JSON document and appends the value
|
|
// of every "certificateFile" field it finds (TLS settings may nest them under
|
|
// several keys depending on the security type).
|
|
func collectCertFiles(streamSettings string, out []string) []string {
|
|
streamSettings = strings.TrimSpace(streamSettings)
|
|
if streamSettings == "" {
|
|
return out
|
|
}
|
|
var parsed any
|
|
if err := json.Unmarshal([]byte(streamSettings), &parsed); err != nil {
|
|
return out
|
|
}
|
|
return walkCertFiles(parsed, out)
|
|
}
|
|
|
|
func walkCertFiles(node any, out []string) []string {
|
|
switch v := node.(type) {
|
|
case map[string]any:
|
|
for key, val := range v {
|
|
if key == "certificateFile" {
|
|
if path, ok := val.(string); ok {
|
|
if path = strings.TrimSpace(path); path != "" {
|
|
out = append(out, path)
|
|
}
|
|
}
|
|
}
|
|
out = walkCertFiles(val, out)
|
|
}
|
|
case []any:
|
|
for _, item := range v {
|
|
out = walkCertFiles(item, out)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// GetRemoteCertHash opens a uTLS (Chrome fingerprint) handshake to a remote
|
|
// endpoint and returns the hex-encoded SHA-256 of its leaf certificate — the
|
|
// value to put in pinnedPeerCertSha256 (pcs) when pinning a server whose
|
|
// certificate file you don't hold (a CDN front, a REALITY dest, an external
|
|
// proxy). A native handshake replaces the old `xray tls ping` subprocess so the
|
|
// real dial/handshake failure (connection refused, timeout, …) surfaces
|
|
// verbatim. `server` may be host or host:port; the port defaults to 443.
|
|
func (s *ServerService) GetRemoteCertHash(server string) ([]string, error) {
|
|
server = strings.TrimSpace(server)
|
|
if server == "" {
|
|
return nil, common.NewError("no server provided")
|
|
}
|
|
|
|
host, port := server, "443"
|
|
if h, p, err := stdnet.SplitHostPort(server); err == nil {
|
|
host, port = h, p
|
|
}
|
|
|
|
dialer := stdnet.Dialer{Timeout: 10 * time.Second}
|
|
tcpConn, err := dialer.Dial("tcp", stdnet.JoinHostPort(host, port))
|
|
if err != nil {
|
|
return nil, common.NewErrorf("failed to dial %s: %s", stdnet.JoinHostPort(host, port), err)
|
|
}
|
|
defer tcpConn.Close()
|
|
_ = tcpConn.SetDeadline(time.Now().Add(15 * time.Second))
|
|
|
|
tlsConn := utls.UClient(tcpConn, &utls.Config{
|
|
ServerName: host,
|
|
InsecureSkipVerify: true,
|
|
NextProtos: []string{"h2", "http/1.1"},
|
|
}, utls.HelloChrome_Auto)
|
|
defer tlsConn.Close()
|
|
if err := tlsConn.Handshake(); err != nil {
|
|
return nil, common.NewErrorf("tls handshake with %s failed: %s", host, err)
|
|
}
|
|
|
|
certs := tlsConn.ConnectionState().PeerCertificates
|
|
if len(certs) == 0 {
|
|
return nil, common.NewError("no certificate returned by ", host)
|
|
}
|
|
// PeerCertificates[0] is always the leaf the connection verifies against —
|
|
// robust for IP-only self-signed certs that carry no DNS SANs.
|
|
sum := sha256.Sum256(certs[0].Raw)
|
|
return []string{hex.EncodeToString(sum[:])}, nil
|
|
}
|
|
|
|
func (s *ServerService) GetNewEchCert(sni string) (any, error) {
|
|
// Run the command
|
|
cmd := exec.CommandContext(context.Background(), xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
lines := strings.Split(out.String(), "\n")
|
|
if len(lines) < 4 {
|
|
return nil, common.NewError("invalid ech cert")
|
|
}
|
|
|
|
configList := lines[1]
|
|
serverKeys := lines[3]
|
|
|
|
return map[string]any{
|
|
"echServerKeys": serverKeys,
|
|
"echConfigList": configList,
|
|
}, nil
|
|
}
|
|
|
|
func (s *ServerService) GetNewVlessEnc() (any, error) {
|
|
cmd := exec.CommandContext(context.Background(), xray.GetBinaryPath(), "vlessenc")
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
if err := cmd.Run(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
auths := parseVlessEncAuths(out.String())
|
|
auths = append(auths, deriveVlessEncModes(auths)...)
|
|
|
|
return map[string]any{
|
|
"auths": auths,
|
|
}, nil
|
|
}
|
|
|
|
func deriveVlessEncModes(auths []map[string]string) []map[string]string {
|
|
var extra []map[string]string
|
|
for _, a := range auths {
|
|
for _, mode := range []string{"xorpub", "random"} {
|
|
dec := strings.Replace(a["decryption"], ".native.", "."+mode+".", 1)
|
|
enc := strings.Replace(a["encryption"], ".native.", "."+mode+".", 1)
|
|
if dec == a["decryption"] && enc == a["encryption"] {
|
|
continue
|
|
}
|
|
extra = append(extra, map[string]string{
|
|
"id": a["id"] + "_" + mode,
|
|
"label": a["label"] + " (" + mode + ")",
|
|
"decryption": dec,
|
|
"encryption": enc,
|
|
})
|
|
}
|
|
}
|
|
return extra
|
|
}
|
|
|
|
func parseVlessEncAuths(output string) []map[string]string {
|
|
lines := strings.Split(output, "\n")
|
|
var auths []map[string]string
|
|
var current map[string]string
|
|
|
|
for _, line := range lines {
|
|
line = strings.TrimSpace(line)
|
|
if strings.HasPrefix(line, "Authentication:") {
|
|
if current != nil {
|
|
auths = append(auths, current)
|
|
}
|
|
label := strings.TrimSpace(strings.TrimPrefix(line, "Authentication:"))
|
|
current = map[string]string{
|
|
"id": vlessEncAuthID(label),
|
|
"label": label,
|
|
}
|
|
} else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
|
|
parts := strings.SplitN(line, ":", 2)
|
|
if len(parts) == 2 && current != nil {
|
|
key := strings.Trim(parts[0], `" `)
|
|
val := strings.TrimSpace(parts[1])
|
|
val = strings.TrimSuffix(val, ",")
|
|
val = strings.Trim(val, `" `)
|
|
current[key] = val
|
|
}
|
|
}
|
|
}
|
|
|
|
if current != nil {
|
|
auths = append(auths, current)
|
|
}
|
|
|
|
return auths
|
|
}
|
|
|
|
func vlessEncAuthID(label string) string {
|
|
normalized := strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.ToLower(label))
|
|
switch {
|
|
case strings.Contains(normalized, "mlkem768"):
|
|
return "mlkem768"
|
|
case strings.Contains(normalized, "x25519"):
|
|
return "x25519"
|
|
default:
|
|
return normalized
|
|
}
|
|
}
|
|
|
|
func (s *ServerService) GetNewUUID() (map[string]string, error) {
|
|
newUUID, err := uuid.NewRandom()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate UUID: %w", err)
|
|
}
|
|
|
|
return map[string]string{
|
|
"uuid": newUUID.String(),
|
|
}, nil
|
|
}
|
|
|
|
func (s *ServerService) GetNewmlkem768() (any, error) {
|
|
// Run the command
|
|
cmd := exec.CommandContext(context.Background(), xray.GetBinaryPath(), "mlkem768")
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
seed, client, err := parseXrayKeyPairOutput(out.String())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
keyPair := map[string]any{
|
|
"seed": seed,
|
|
"client": client,
|
|
}
|
|
|
|
return keyPair, nil
|
|
}
|