Commit Graph
41 Commits
  • fix(script): confirm auto-detected public IPv4 before issuing IP certificate
    On networks with asymmetric routing (or proxies/multi-WAN), external
    IP-echo services can return a transit or gateway address instead of the
    server's real incoming IP, and every IP-certificate flow silently
    issued for that wrong address. The x-ui.sh menu flow (option 20 -> 6)
    and the install.sh/update.sh SSL menus now show the detected IPv4 for
    confirmation (Enter keeps the old behavior), and declining falls into
    the same validated manual-entry loop already used when every provider
    fails. Non-interactive installs are untouched - XUI_SERVER_IP already
    pins the address there.
    
    Closes #5867
  • feat(mtproto): adopt dolonet/mtg-multi and make MTProto inbounds multi-client
    Replace the upstream 9seconds/mtg sidecar with the dolonet/mtg-multi fork so a single MTProto inbound can serve many per-user secrets. Each panel client is now one named FakeTLS secret in the fork's [secrets] section: clients are first-class (attach/detach, limits, expiry, per-client tg:// links) exactly like every other protocol, mirroring the WireGuard multi-client model. Per-client traffic and online status come from the fork's /stats JSON API (its Prometheus output has no per-user label), fed into the existing email-keyed client_traffics accumulator; an optional throttle caps concurrent connections. A one-time seeder converts each legacy single-secret inbound into a one-client inbound.
    
    The fork ships only linux/darwin amd64/arm64 binaries but is pure Go, so provisioning builds it from source for every supported platform (release.yml, DockerInit.sh) while keeping the panel-expected mtg-<os>-<arch> filename and the 'run' verb, so process.go is untouched. Also fixes a pre-existing update.sh gap that never renamed the mtg binary for armv6/armv7 updates.
  • fix(script): stop logging an error when Enter accepts the default ACME port
    Pressing Enter at the 'Please choose which port to use (default is 80)' prompt left WebPort empty, and bash arithmetic treats an empty string as 0, so the out-of-range branch fired and printed 'Your input is invalid' even though the default was correctly applied. Handle empty input as accepting the default silently, and validate real input with a digits-only regex so non-numeric entries like '8x' get the invalid-input message instead of a bash arithmetic error. Applied to the identical prompt in x-ui.sh, install.sh, and update.sh.
    
    Fixes #5829
  • fix(script): rename the Xray binary to xray-linux-arm32 on 32-bit ARM
    The panel maps GOARCH=arm to "arm32" and launches bin/xray-linux-arm32,
    but install.sh/update.sh renamed the release tarball's binary
    (xray-linux-armv5/v6/v7) to xray-linux-arm. On armv7 boxes every update
    downloaded a fresh Xray core into a name the panel never executes, so an
    old correctly-named binary kept running forever, and a brand-new install
    had no launchable Xray binary at all. Rename to arm32 to match the panel
    (mtg stays plain "arm", matching internal/mtproto), and drop the stale
    misnamed xray-linux-arm during updates like the existing amd64 cleanup.
    
    Closes #5788
  • fix(script): stop running full system upgrades via pacman -Syu on Arch
    Installing or updating the panel on Arch/Manjaro/Parch performed a full
    system upgrade (pacman -Syu) instead of only refreshing the package
    database and installing the needed packages, unlike every other distro
    branch (apt-get update, dnf makecache, zypper refresh, apk update).
    Unrequested full upgrades can pull in kernel and system updates the
    user never asked for. Align all pacman calls on the -Sy --noconfirm
    form already used elsewhere in these scripts.
    
    Closes #5810
  • fix: make all self-managed file downloads/installs atomic, with real completion status (#5711)
    * fix(script): download the live x-ui.sh script atomically before replacing it
    
    update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote
    /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same
    inode a currently-running x-ui process may still be reading from. A
    network hiccup or slow write during that overwrite leaves a
    half-old/half-new script on disk, which then fails with bogus syntax
    errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into
    place instead, matching the atomic pattern install.sh already uses.
    
    Also fixes update_menu() checking chmod's exit code instead of curl's,
    which meant a failed download could still report "Update successful."
    
    * fix(script): close remaining gaps in the atomic script-update path
    
    Code review of the previous commit found the atomic mv fix was itself
    incomplete:
    
    - None of the mv -f calls checked their exit status, so a failed move
      fell through to chmod and "success" messaging while /usr/bin/x-ui
      stayed on the old file.
    - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z
      got a 304, nothing to do" from "a stale temp file survived an
      earlier crashed run" -- the latter could get moved into place with
      no freshness check.
    - update_menu(), update_shell(), and update_x-ui() all hardcoded the
      same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a
      cron auto-update racing an interactive menu update) could collide.
    - update.sh's update_x-ui() was missing the non-empty-file guard
      update_shell() already had.
    
    x-ui.sh's update_menu() and update_shell() now share a
    replace_xui_script() helper that uses a PID-suffixed temp path
    (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and
    checks the exit status of curl, the non-empty test, and mv before
    treating the update as successful. update.sh's update_x-ui() gets the
    same sequence inlined (it's fetched as a standalone script and can't
    call x-ui.sh's function), closing the missing-guard gap and using its
    own unique temp path.
    
    * fix(script,panel): harden the remaining self-update download paths
    
    install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two
    already-fixed scripts had: no exit-status check on mv, and a fixed temp
    name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it
    its own PID-suffixed temp path, an empty-file guard, and an mv
    exit-status check, matching the pattern used there.
    
    Audited the web dashboard's Go-native updater (panel.go) for the same
    bug class: it already uses os.CreateTemp for a genuinely unique temp
    file and cleans up via both a deferred Remove and a shell EXIT trap, so
    it was never exposed to the fixed-path race. It was missing a check
    for a zero-byte download (a 200 OK with an empty body would chmod +x
    and exec an empty script) -- added that alongside the existing size
    cap.
    
    Not addressed here: once startUpdate()'s child process starts, the Go
    service releases it and returns success immediately. If update.sh
    fails partway through, the still-running old panel keeps answering
    /status, so the frontend's poll can report success with no update
    having happened. Fixing that needs update.sh to signal completion
    status back and the frontend to check it -- a separate follow-up.
    
    * feat(panel): report real completion status for the web self-update
    
    Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once
    startUpdate() launches update.sh detached, the Go service had no way to
    learn whether it actually succeeded. If update.sh failed partway
    (network drop, disk full, permission denied), the still-running old
    panel kept answering /status, so the frontend's poll reported success
    with nothing having changed.
    
    update.sh now writes its outcome to a small JSON status file
    (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which
    covers every exit path in the script -- including the two bare `exit 1`
    call sites that don't go through the existing _fail() helper. The Go
    service generates a run ID before launching, passes it and the status
    path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a
    new GET /panel/api/server/getUpdateStatus endpoint reports it back. The
    frontend now polls that instead of blindly trusting HTTP reachability,
    and shows a distinct error or "couldn't confirm" message instead of
    silently reloading into a false success.
    
    Adversarial review of this surfaced three more issues, fixed here:
    - No lock stopped two concurrent /updatePanel calls from launching two
      update.sh runs that would race each other on the actual update work
      (tar extraction, service unit swap). Added an in-memory guard with a
      5-minute self-expiring window, so a run that never reaches a terminal
      state doesn't lock out retries indefinitely.
    - XUI_UPDATE_RUN_ID is read from the environment and was interpolated
      unquoted into the status JSON; a malformed value would produce
      invalid JSON. Now validated as digits-only before use.
    - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON
      number it would lose precision in JavaScript (past
      Number.MAX_SAFE_INTEGER), letting two different runs round to the
      same value on the wire and defeat the whole comparison. It's now a
      decimal string end to end (Go, the status file, and the generated
      frontend type).
    
    install.sh's equivalent temp-file/mv path and the Go-native
    downloadPanelUpdater() path were audited for the same bug classes
    during this work; findings from that audit were addressed separately.
    
    * fix(panel): release the update lock as soon as the run finishes
    
    An exhaustive multi-angle review of the whole branch (12 finder angles,
    3-vote adversarial verification, a fresh-eyes sweep) surfaced a real
    bug in the concurrency guard added in the previous commit, plus several
    smaller issues; this fixes what's actionable now.
    
    The bug: acquireUpdateSlot only ever released on the 5-minute stale
    timeout or if launching itself failed. If update.sh launched fine but
    failed fast (bad GitHub API response, "x-ui not installed", any of its
    early exit paths), the status file correctly reported "failed" within
    seconds, but a retry was still rejected with "a panel update is
    already in progress" for up to 5 more minutes -- the guard never
    looked at the very status file this branch built to know a run was
    done. It now tracks which run ID currently holds the slot and checks
    that run's own status before falling back to the timeout, so a fast
    failure clears the way for an immediate retry. Added a regression test
    for this, plus one confirming a stale, unrelated runID can't be
    mistaken for the current run finishing.
    
    Also:
    - Added a genuinely concurrent test for the guard: 200 goroutines
      racing acquireUpdateSlot, asserting exactly one wins. The previous
      tests only ever called it from one goroutine, so they gave no signal
      if the mutex's check-then-set were silently broken -- verified this
      by temporarily removing the lock and confirming the old tests still
      passed while the new one caught it immediately under -race.
    - Removed the redundant upfront "pending" status write: GetUpdateStatus
      already defaults a missing/stale file to pending, and the frontend
      matches by run ID regardless, so the write changed no observable
      behavior. Deleted writeUpdateStatus entirely since that was its only
      caller.
    - Renamed replace_xui_script()'s unclear "conditional" parameter to
      use_if_modified_since, matching what it actually controls.
    - Added HTTP-level tests for the new getUpdateStatus endpoint,
      including a regression test that the runId wire format is a JSON
      string (decoding into a Go string field fails outright if it were
      ever a bare number). updatePanel's actual launch path is not
      covered: on a Linux test runner it would make a real network call
      and could exec a real update.sh, so only its non-Linux guard path is
      safely testable without mocking.
    
    Not fixed here, tracked separately: the same unsafe-overwrite pattern
    this branch eliminated for /usr/bin/x-ui is still present for the
    systemd unit file install in update.sh and install.sh (lower severity
    since systemd only reads it on daemon-reload, not continuously); and
    startUpdate's systemd-run-vs-detached-fallback branching has no test
    coverage since testing it safely needs dependency injection this fix
    doesn't warrant bundling in.
    
    * fix(script): make systemd unit file installation atomic
    
    Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every
    site that lands the systemd unit at ${xui_service}/x-ui.service --
    copying it from the extracted release tarball, or falling back to a
    GitHub download per distro family -- wrote straight onto the live
    path via cp/curl, no temp file, no verification. A network drop
    mid-download or an interrupted cp leaves the unit file truncated;
    systemd then fails to parse it on the next daemon-reload/start,
    leaving the panel unable to come up until an operator manually
    re-copies a good unit file.
    
    Lower severity than the /usr/bin/x-ui case (systemd only reads this
    file on demand at daemon-reload time, not continuously the way bash
    interprets a running script line by line), but it's the identical
    gap, just left uncovered when that fix landed.
    
    Added a small shared helper in both update.sh and install.sh --
    _install_xui_service_unit() -- covering both source types (cp from
    the tarball, curl from GitHub): write to a PID-suffixed temp file,
    verify the copy/download succeeded and the result is non-empty, then
    mv -f into place and check that exit status too, matching the pattern
    already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl
    fallback in each file now go through it; verified no other site
    writes new content to the unit path (the remaining ${xui_service}
    references are a pre-install existence check, an rm during old-version
    cleanup, and the chown/chmod that already ran after the file is safely
    in place -- none of those need atomicity).
    
    Verified with bash -n on both files, plus a standalone scratch test
    exercising cp-success, cp-with-missing-source, cp-with-empty-source,
    and curl-failure paths: on every failure the previous, good unit file
    content is left untouched and no temp file is leaked behind.
    
    * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment
    
    A final maximum-rigor review of the whole PR (12 finder angles including
    a repo-wide sweep for any remaining instance of the bug class this PR
    fixes) found two more real issues:
    
    - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare
      `curl -fLRo` straight onto the live path in both update.sh and
      install.sh -- the exact same unguarded-overwrite pattern already
      fixed for /usr/bin/x-ui and the systemd unit file, just left
      uncovered on the OpenRC side. A network drop mid-download truncates
      the live init script; OpenRC then fails to source/execute it on the
      next start, leaving the panel unable to come up. Fixed with the same
      temp-file + non-empty check + mv -f (with its own exit-status check)
      pattern used everywhere else in this PR. Verified with bash -n and a
      standalone scratch-script test covering success, empty-download, and
      destination-preserved-on-failure paths.
    
    - internal/web/service/panel/panel_test.go had one line-level `//`
      comment on a call site, which the root CLAUDE.md's hard rule ("No //
      line comments in committed Go/TS... rename instead of annotating")
      explicitly prohibits. The comment duplicated context already stated
      in the test's own doc comment two lines above, so it's simply
      removed rather than reworded.
    
    Also flagged, deliberately not bundled here since it's a different
    subsystem: x-ui.sh's update_geofiles() downloads Xray's live
    geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked
    as its own follow-up.
    
    * fix(script): make geo-data file downloads atomic
    
    Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the
    Alpine init script fixed in prior PRs: update_geofiles() downloaded
    Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl
    writing straight onto the exact path Xray reads at runtime
    (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp
    file, no verification. The existing check only inspected the reported
    HTTP status via -w '%{http_code}', not file integrity, so a network
    drop mid-download could leave a truncated .dat file on disk that
    passes the status check. Xray then fails to parse it on the next
    restart/reload, breaking any routing rules that reference geoip:/
    geosite:.
    
    The -z conditional-GET usage needed care here: the original code
    pointed both -z and -o at the same live path. Fixed by pointing -z at
    the live file (to keep the "already current" freshness check) while
    -o writes to a PID-suffixed temp file, matching the pattern already
    proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP
    server that a 304 response leaves the temp file untouched/nonexistent
    (so the existing "already up to date" branch still works unchanged),
    and added a non-empty check plus a checked mv -f before treating a
    download as installed.
    
    Verified with bash -n and an end-to-end scratch test against a local
    server covering: fresh download, 304-not-modified, empty response
    body, and a 404 -- confirming a failure at any stage leaves the
    previous good .dat file completely untouched and no temp file behind.
    
    * fix(script): verify the release tarball extraction, not just the download
    
    The final maximum-rigor review found the most significant remaining gap
    in this whole effort: update.sh and install.sh check the tarball
    download's exit status, but never check tar's exit status, and never
    verify the extracted x-ui binary actually exists before continuing.
    Worse, by the time extraction runs, the previous installation has
    already been stopped and deleted -- there's no rollback. A truncated
    download that still passes curl's own check, or a tar failure (disk
    full, killed process), left the panel silently in a broken half-state:
    chmod/config/service-install all continued to run against a missing or
    empty binary, with no error surfaced anywhere. This is the same bug
    class as everything else in this PR (unverified write to a path
    something then depends on), just for the tarball itself rather than a
    single file -- and it also covers the geo-data files this PR already
    fixed once for the interactive/cron path, since they ship inside this
    same tarball on every panel update.
    
    Added: a non-empty check on the downloaded archive (both files, both
    install.sh call sites) and a check that tar succeeded and produced a
    non-empty x-ui binary before proceeding, failing loudly with a message
    that explicitly says the previous install is already gone, since
    silently continuing here is worse than anywhere else in this PR.
    
    This doesn't make the multi-file extraction fully atomic (that would
    mean extracting to a temp directory and atomically swapping the whole
    install tree into place, a materially larger restructuring than
    anything else in this PR) -- but it closes the "fails silently, user
    discovers it days later when Xray can't start" gap, which was the
    actual reported problem this whole effort traces back to.
    
    Also fixed, all much smaller:
    - replace_xui_script() in x-ui.sh implicitly returned chmod's exit
      status instead of success, so a successful atomic install could be
      reported as failed if chmod transiently failed after the mv already
      landed the new script. Added an explicit `return 0`.
    - update_geofiles() had no default case branch; an unrecognized
      argument would silently reuse whatever dat_files/dat_source values a
      previous call left in the un-scoped globals instead of failing.
      Currently unreachable (all three call sites pass fixed literals) but
      cheap, defensive, and worth having.
    - internal/web/controller/server.go's updatePanel has one branch (an
      unparseable "dev" form value) that's both untested and safe to test
      on any platform, since it's rejected before any real exec/network
      call. Added the missing test case.
    
    Verified: bash -n on all three scripts; an empirical scratch test
    covering an empty downloaded archive, a corrupt (non-gzip) archive,
    and a successfully-extracting-but-empty archive, confirming each is
    caught before the script proceeds; full go build/vet/test -race
    across the whole module; frontend generation confirmed still in sync.
    
    * fix(panel): base the update-slot staleness fallback on process liveness
    
    Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711).
    
    Blocking finding: acquireUpdateSlot's staleness fallback freed the
    update slot purely on elapsed wall-clock time (5 minutes), with no
    check on whether the update.sh process it launched was actually still
    running. update.sh runs install_base() (apt-get/dnf/pacman update and
    install) before update_x-ui even starts, plus several GitHub
    downloads (release tarball, x-ui.sh, and possibly a service unit or
    x-ui.rc) -- on a slow or throttled host, a small VPS being the typical
    deployment target for this project, that alone can plausibly exceed 5
    minutes with nothing wrong. A second /updatePanel call arriving in
    that window (an admin retrying after the frontend's 90s poll times
    out, or overlapping master-node bulk-update calls) would launch a
    second update.sh, racing the exact rm/tar/mv/systemctl sequence this
    whole PR exists to make safe.
    
    Fixed by recording the launched process's PID (detached-fallback path
    only; the systemd-run path's own process has already exited by the
    time startUpdate returns, so it never learns update.sh's real PID) and
    checking it via the standard POSIX kill(pid, 0) liveness probe before
    treating a run as stale, following the existing panel_unix.go /
    panel_other.go platform-split pattern already used for
    setDetachedProcess. A confirmed-alive process now keeps the slot held
    past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline
    for the systemd-run path, which still has no way to check liveness
    directly). updateHardCeiling (2 hours) is an absolute backstop so a
    genuinely wedged run can never lock out retries permanently even on
    the PID-tracked path.
    
    Added two regression tests exercising the new logic (gated to Linux,
    since processAlive is a no-op stub elsewhere): a live PID keeps the
    slot held past the stale window, and the hard ceiling overrides
    liveness. Traced both by hand against the new acquireUpdateSlot logic;
    could not execute-verify processAlive itself on this Windows dev
    machine (no WSL distro installed, and installing one felt
    disproportionate to validate kill(pid, 0), an extremely well-established
    POSIX primitive), but cross-compiled clean for linux/amd64 and this
    repo's CI runs the real test suite on Linux.
    
    Also fixed, both suggestions from the same review:
    - install.sh: two failure paths right after tarball extraction were
      exiting without cleaning up the already-downloaded x-ui.sh temp file
      (xui_script_temp), leaving it behind. Every other new failure branch
      in this PR removes its temp file before exiting; these two now do
      too.
    - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry
      did not reflect that a successful response now carries an obj with
      runId. Added an inline response example matching the existing
      pattern used for other ad hoc (non-schema-backed) responses like
      getWebCertFiles.
    
    Verified: go build/vet clean on both windows (native) and a linux/amd64
    cross-compile; full go test ./... clean; go test -race on the panel
    and controller packages; bash -n on all three shell scripts; npm run
    gen confirms the openapi.json diff is exactly the new response example
    with no stray changes to src/generated; TestAPIRoutesDocumented still
    passes.
  • fix(scripts): pass --force to acme.sh --installcert so it survives sudo
    acme.sh guards every non-install command behind _checkSudo: when a
    non-root user runs the panel scripts via sudo, it prints the sudo wiki
    warning and exits before doing anything, unless FORCE is set. All our
    --issue calls already pass --force and were unaffected, but none of the
    --installcert calls did, so issuance succeeded and installation then
    aborted silently, ending in "Certificate files not found after
    installation". FORCE has no other effect on the installcert path, so
    mirror the --issue calls and pass --force everywhere we install certs.
    
    Closes #5741
  • feat(update): add rolling dev update channel for per-commit builds
    Adds an opt-in Dev channel so panels running CI per-commit builds can self-update to the latest commit, mirroring the stable online-update flow.
    
    CI publishes/overwrites a single fixed-tag pre-release (dev-latest), force-moved to the newest main commit and marked --latest=false so releases/latest stays the stable tag. Builds stamp the short commit via -ldflags; the panel compares the running commit to the dev release commit to detect an update, and update.sh honors XUI_UPDATE_TAG to install from that tag. Linux/systemd only.
  • feat(iplimit): auto-install fail2ban on install and update
    IP limit enforcement is gated on fail2ban being present (ce8b1bed), but the bare-metal install.sh/update.sh never installed it, so the feature stayed disabled until the user ran the IP Limit menu by hand. Docker already auto-configures it; bare-metal hosts did not.
    
    Extract the fail2ban install + jail setup out of install_iplimit into a non-interactive setup_fail2ban_iplimit() (no exit/before_show_menu, returns a status) exposed via 'x-ui setup-fail2ban', and call it from install.sh and update.sh after the panel is up. update.sh is the primary update path (x-ui update and the panel self-updater both run it). Honors XUI_ENABLE_FAIL2BAN (proceed only when unset or true, matching the Go gate) and is non-fatal so a fail2ban failure never aborts the install/update.
  • fix(install): support IPv6-only hosts (#5487)
    * fix(install): support IPv6-only hosts
    
    * fixup: complete IPv6-only install and update support
    
    * fixup: remove no-op download retries
  • fix(script): SSL management fixes (#4994, #5010, #5070)
    - Issue acme.sh HTTP-01 over IPv4 unless the host has no global IPv4
      address: the hardcoded --listen-v6 started a v6-only standalone
      listener, so validation of a domain whose A record points at this
      host always failed (#4994).
    - Add a custom cert/key path option to the "Set Cert paths" menu so
      certificates living outside /root/cert (e.g. certbot under
      /etc/letsencrypt) can be wired to the panel from the CLI (#5010).
    - Derive the displayed Access URL from the certificate's actual SAN
      list instead of the cert folder name, list the other covered names,
      and show the panel's custom-path certificate in "Show Existing
      Domains" (#5070). Also silence find when /root/cert doesn't exist.
  • fix(update): restart panel after regenerating webBasePath to fix login desync
    When update.sh regenerates a short webBasePath, it writes the new path to the
    database after the panel is already running with the old path loaded in memory.
    Without a restart the server keeps serving the old path while the UI shows the new
    one, making the new path unreachable.
  • fix(mtproto): reap orphaned mtg, fix SysLog viewer, mtg log visibility, export remark (#5105) (#5107)
    * fix(logs): render journalctl output in the SysLog viewer
    
    The log viewer's parseLogLine only understood the app-log format
    (2006/01/02 15:04:05 LEVEL - body). With SysLog ticked the backend
    returns journalctl lines (Mon DD HH:MM:SS host ident[pid]: LEVEL - body),
    so the parser mistook the journal time for the level and dropped the
    body, leaving only timestamps. Detect and strip the journald prefix,
    keep the journal timestamp as the stamp, then parse the real level and
    body from the remainder.
    
    * feat(mtproto): surface mtg output and add status reporting
    
    mtg's stdout/stderr was captured by a writer that kept only the last
    line and showed it nowhere, so the reason a proxy could not reach
    Telegram was invisible. Stream mtg output line-by-line into the x-ui
    log, tagged per inbound, so it appears in the panel log viewer and
    journald.
    
    Also fix mangled log lines: logger.Info uses fmt.Sprint, which drops
    the space between adjacent string operands, producing output like
    'inbound3on0.0.0.0:8443'. Switch the affected mtproto calls to the
    formatted (*f) variants.
    
    Add show_mtproto_status to x-ui.sh so 'x-ui status' reports each
    mtproto inbound's mtg process state and bind address.
    
    * fix(logs): parse all journalctl message shapes in SysLog viewer
    
    Real journalctl output mixes four message shapes after the
    'Mon DD HH:MM:SS host ident[pid]:' prefix: go-logging 'LEVEL - msg'
    (x-ui/xray), Go std-log with an embedded date (net/http, runtime),
    telego's '[timestamp] LEVEL msg', and systemd lines. The viewer only
    understood the first, so std-log and telego lines — which never contain
    ' - ' — collapsed to a bare timestamp (e.g. the 8s telego 409 spam).
    
    Extract the parser into a pure, testable module and teach it the other
    shapes: strip the redundant Go std-log date, lift the level out of
    telego brackets, and always keep the message body. Add a unit test
    covering each shape with real captured lines.
    
    * fix(mtproto): reap orphaned mtg sidecars so a stale one can't break new clients
    
    On Linux x-ui does not kill its mtg children when it dies (no kill-on-exit,
    unlike the Windows job object). After a crash, OOM, kill -9, or update, a
    stale mtg keeps holding the inbound port with an OLD secret, so new clients
    fail the FakeTLS handshake and get silently domain-fronted to the fakeTLS
    domain instead of proxied to Telegram (a few MB of traffic, never connects).
    
    Sweep orphans at startup: on the first reconcile, before x-ui starts any of
    its own mtg, scan /proc and SIGKILL any process whose executable is our
    mtg-<goos>-<goarch> binary. x-ui is the sole owner of mtg, so anything alive
    then is an orphan. Runs once per process (swept guard), survives the
    binary-deleted-during-update case via /proc/<pid>/cmdline, and is a no-op on
    Windows (job object) and other platforms.
    
    Also clear stray mtg in update.sh/install.sh after stopping x-ui, anchored to
    the 'mtg-linux-<arch> run ' invocation so the pattern can't match unrelated
    command lines (e.g. x-ui.sh's own 'grep mtg-linux').
    
    * fix(logs): drop dead body initializer flagged by eslint no-useless-assignment
    
    * fix(mtproto): drop remark fragment from tg://proxy export link
    
    The mtproto export link appended the inbound remark as a URL fragment
    (tg://proxy?server=...&port=...&secret=...#remark). Telegram Desktop
    rejects a proxy deep link with a trailing fragment as 'This proxy link
    is invalid', breaking one-click import, and a remark is meaningless for
    proxy links across clients. Stop adding it in both the panel link
    (genMtprotoLink) and the subscription service. Fixes #5105.
    
    * fix(x-ui.sh): remove unused check_mtproto_status helper
    
    show_mtproto_status does its own process check, so check_mtproto_status
    was dead code. Drop it (per Copilot review on #5107).
  • feat(bash): prompt for PostgreSQL (#4472)
    * feat(install): prompt for SQLite vs PostgreSQL during install
    
    * fix(install): write env file to per-distro path and handle pg-install failure
    
    The env file was hardcoded to /etc/default/x-ui, but RHEL/Fedora units read
    /etc/sysconfig/x-ui, Arch reads /etc/conf.d/x-ui, and Alpine OpenRC auto-
    sources /etc/conf.d/x-ui. PostgreSQL selection was silently dropped on every
    distro except Debian. Also initdb on openSUSE (service wouldn't start) and
    prompt the operator on local-install failure instead of silently demoting
    to SQLite.
    
    * fix(scripts): make x-ui.sh and update.sh PostgreSQL-aware
    
    update.sh ran setting -show and migrate without sourcing the env file, so
    PostgreSQL users had migrations applied to the SQLite default and settings
    introspection read the wrong DB. Sourcing the per-distro env file at the
    start of update_x-ui exports XUI_DB_TYPE/XUI_DB_DSN to all binary calls.
    
    x-ui.sh now shows the active backend in View Current Settings (password
    masked) and removes the env file on uninstall so a later reinstall doesn't
    inherit a stale DSN.
  • fix(scripts): harden server-IP detection with multi-provider + manual fallback
    Try six IPv4 providers in turn, accept only HTTP 200 + IPv4-shaped body,
    and prompt the user to enter their IP if every provider fails.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
  • fix: enhance WebSocket stability, resolve XHTTP configurations and fix UI loading shifts (#3997)
    * feat: implement real-time traffic monitoring and UI updates using a high-performance WebSocket hub and background job system
    
    * feat: add bulk client management support and improve inbound data handling
    
    * Fix bug
    
    * **Fixes & Changes:**
    1. **Fixed XPadding Placement Dropdown**:
       - Added the missing `cookie` and `query` options to `xPaddingPlacement` (`stream_xhttp.html`).
       - *Why:* Previously, users wanting `cookie` obfuscation were forced to use the `header` placement string. This caused Xray-core to blindly intercept the entire monolithic HTTP Cookie header, failing internal padding-length validations and causing the inbound to silently drop the connection.
    2. **Fixed Uplink Data Placement Validation**:
       - Replaced the unsupported `query` option with `cookie` in `uplinkDataPlacement`.
       - *Why:* Xray-core's `transport_internet.go` explicitly forbids `query` as an uplink placement option. Selecting it from the UI previously sent a payload that would cause Xray-core to instantly throw an `unsupported uplink data placement: query` panic. Adding `cookie` perfectly aligns the UI with Xray-core restrictions.
    ### Related Issues
    - Resolves #3992
    
    * This commit fixes structural payload issues preventing XHTTP from functioning correctly and eliminates WebSocket log spam.
    - **[Fix X-Padding UI]** Added missing `cookie` and `query` options to X-Padding Placement. Fixes the issue where using Cookie fallback triggers whole HTTP Cookie header interception and silent drop in Xray-core. (Resolves [#3992](https://github.com/MHSanaei/3x-ui/issues/3992))
    - **[Fix Uplink Data Options]** Replaced the invalid `query` option with `cookie` in Uplink Data Placement dropdown to prevent Xray-core backend panic `unsupported uplink data placement: query`.
    - **[Fix WebSockets Spam]** Boosted `maxMessageSize` boundary to 100MB and gracefully handled fallback fetch signals via `broadcastInvalidate` to avoid buffer dropping spam. (Resolves [#3984](https://github.com/MHSanaei/3x-ui/issues/3984))
    
    * Fix
    
    * gofmt
    
    * fix(websocket): resolve channel race condition and graceful shutdown deadlock
    
    * Fix: inbounds switch
    
    * Change max quantity from 10000 to 500
    
    * fix
  • Fix SSL domain setup on reinstall: reuse existing certs and avoid false success/failure logs (#4004)
    * perf: replace /dev/urandom | tr with openssl rand to fix CPU spike
    
    * fix: add cron to default package installation and improve SSL certificate handling
    
    * Reworked `--installcert` success criteria, cleanup behavior adjusted.
  • Require HTTP 200 from curl before using IP
    Replace simple curl+trim checks with a response+http_code parse to ensure the remote URL returns HTTP 200 and a non-empty body before assigning server_ip. Changes applied to install.sh, update.sh and x-ui.sh: use curl -w to append the status code, extract http_code and ip_result, and only set server_ip when http_code == 200 and ip_result is non-empty. This makes the IP discovery more robust against error pages or partial responses while keeping the existing timeout behavior.
  • Add x-ui.service.arch file (#3650)
    * Add a service file for Arch-based OSs
    
    * Update release.yml with arch service file
    
    * Update x-ui.service.arch
  • Add port selection and checks for ACME HTTP-01 listener
    Introduces user prompts to select the port for ACME HTTP-01 certificate validation (default 80), checks if the chosen port is available, and provides guidance for port forwarding. Adds is_port_in_use helper to all scripts and improves messaging for certificate issuance and error handling.
  • fix
  • Remove wget dependency from everywhere (#3598)
    * Remove wget dependency
    
    * Merge branch 'curl_only' of https://github.com/nebulosa2007/3x-ui into nebulosa2007-curl_only
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • Set variables for packaging purposes (#3600)
    * Set Variables for settings
  • Added EnvironmentFile to systemd unit (#3606)
    * Added EnvironmentFile to systemd unit
    
    * Added support for older releases
    
    * Remove ARGS
    
    * Fixed copy unit
    
    * Fixed unit filename
    
    * Update update.sh
  • Set log folder variable to /var/log/3x-ui (#3599)
    * Set log folder variable to /var/log/3x-ui
    
    * Set log folder as x-ui and create the log folder
    
    * Create the log folder in install and update scripts
  • fix
  • Update for Red Hat base Linux (#3589)
    * Update install.sh
    
    * Update update.sh
    
    * Update x-ui.sh
    
    * Update install.sh
    
    * Update update.sh
    
    * Update x-ui.sh
    
    * fix
  • Add update-all-geofiles key to x-ui.sh (#3586)
    * added update-all-geofiles key to x-ui.sh that updated all geofiles
    
    * fix
    
    * text fixes
    
    * typo fix
    
    * cleanup
  • Add support for OpenSUSE Leap (#3573)
    * Update update.sh
    
    * Update install.sh
    
    * Update x-ui.sh
    
    * Update x-ui.sh
  • feat: Add update script (#3555)
    * feat: Add update script
    
    * Small fix
    
    * Fixed typo
    
    * Fixed typo
    
    * chmod +x
    
    * Update x-ui
    
    * Fixed update message
    
    * Fixed typo
    
    * Added downloading via IPv4
    
    * Remove check_glibc_version
    
    * Fixed self destroy
    
    * Fixed typo
    
    * Fixed self destroy
    
    ---------