mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-06-28 00:24:19 +00:00
41645255f1
* refactor(service): split client.go into focused files
client.go had grown to 4455 lines mixing ~10 responsibilities. Split it
verbatim into cohesive same-package files (no behavior change):
client.go foundation: ClientService, ClientWithAttachments,
ClientCreatePayload, ErrClientNotInInbound, sqlInChunk
client_locks.go inbound mutation locks, delete tombstones, compactOrphans
client_lookup.go read-only lookups (GetByID, List, EffectiveFlow, ...)
client_link.go inbound association sync (SyncInbound, DetachInbound, ...)
client_crud.go single-client CRUD + validation + protocol defaults
client_inbound_apply.go low-level inbound-settings mutators + by-email setters
client_bulk.go bulk attach/detach/adjust/delete/create + DelDepleted
client_traffic.go traffic-reset paths
client_groups.go client group management
client_paging.go paged listing, filtering, sorting, summary
Every declaration moved unchanged (verified: identical func/type/const/var
signature set before vs after). Imports redistributed per file via goimports.
go build ./..., go vet, and go test ./web/service/... all pass.
* refactor(service): split inbound.go into focused files
inbound.go was 4100 lines. Split it verbatim into cohesive same-package
files (no behavior change):
inbound.go core inbound CRUD + InboundService (keeps pkg doc)
inbound_protocol.go protocol / stream capability helpers
inbound_node.go node/runtime/remote coordination + online tracking
inbound_traffic.go traffic accounting, reset, client stats
inbound_client_ips.go per-client IP tracking
inbound_clients.go client lookups within inbounds + copy-clients
inbound_disable.go auto-disable invalid inbounds/clients
inbound_migration.go DB migrations
inbound_sublink.go subscription link providers
inbound_util.go generic slice/string helpers
Identical func/type/const/var signature set before vs after; package doc
comment preserved on inbound.go. Imports redistributed via goimports.
Build, vet, and go test ./web/service/... all pass.
* refactor(service): split tgbot.go into focused files
tgbot.go was 3738 lines dominated by a 1246-line answerCallback. Split it
verbatim into cohesive same-package files (no behavior change):
tgbot.go lifecycle, bot setup, caches, small utils
tgbot_router.go incoming update / command / callback dispatch
tgbot_send.go outbound messaging primitives
tgbot_client.go client views, actions, subscription links
tgbot_inbound.go inbound listing / pickers
tgbot_report.go server usage, exhausted, online, backups, notifications
Identical func/type/const/var signature set before vs after. Imports
redistributed via goimports. Build, vet, and go test ./web/service/... pass.
* refactor(client): dedupe single-field by-email setters
ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, and
ResetClientTrafficLimitByEmail shared an identical ~50-line body that
resolves the inbound by email, confirms the client exists, rewrites a
single-client settings payload, and delegates to UpdateInboundClient.
Extract that into applyClientFieldByEmail(inboundSvc, email, mutate) and
reduce each setter to a 3-line wrapper. Behavior is unchanged: same checks
and error strings, same single-client payload contract, same totalGB guard.
SetClientTelegramUserID (resolves by traffic id, different error text) and
ToggleClientEnableByEmail/SetClientEnableByEmail (different return shape and
a pre-read of the old state) intentionally keep their own bodies.
* refactor(service): extract panel/ subpackage
Move the panel-administration leaf services out of the flat service
package into web/service/panel/ (package panel):
user.go UserService (auth / 2FA / LDAP)
panel.go PanelService (restart / self-update) + version helpers
panel_other.go non-unix RestartPanel
panel_unix.go unix RestartPanel
api_token.go ApiTokenService
websocket.go WebSocketService
panel_test.go version/shellQuote unit tests
These are leaves: they depend on core (SettingService, Release) but no
core file references them, so the extraction creates no import cycle.
Core references are now qualified (service.SettingService, service.Release);
callers in main.go, web/web.go, and web/controller/* updated to panel.*.
Build, vet, and go test ./web/... pass.
* refactor(service): extract integration/ subpackage
Move the external-provider integration leaves into web/service/integration/
(package integration):
warp.go WarpService (Cloudflare WARP)
nord.go NordService (NordVPN)
custom_geo.go CustomGeoService (custom geo asset management)
*_test.go custom_geo / panel-proxy tests
These depend on core (SettingService, ServerService, XraySettingService) but
no core file references them. xray_setting.go stays in core because it calls
the unexported SettingService.saveSetting. The shared isBlockedIP SSRF helper
(used by core url_safety.go and by custom_geo) now has a small copy in each
package rather than being exported. Core references qualified; callers in
web/web.go, web/job/*, and web/controller/* updated to integration.*.
Build, vet, and go test ./web/... pass.
* refactor(service): extract tgbot/ subpackage
Move the Telegram bot (6 files + test) into web/service/tgbot/ (package
tgbot). It is a leaf: it embeds five core services (Inbound/Client/Setting/
Server/Xray) and the core never references it, so no import cycle.
To support the package boundary without changing behavior:
- core exposes XrayProcess() *xray.Process so tgbot keeps calling the
exact same running-process methods it used via the package-level `p`;
- three core methods tgbot calls are exported: ClientService.checkIs-
EnabledByEmail -> CheckIsEnabledByEmail, InboundService.getAllEmails ->
GetAllEmails (callers updated in-package);
- tgbot's embedded-field types and the few core type refs (Status,
ClientCreatePayload, SanitizePublicHTTPURL) are now service-qualified.
Callers in main.go, web/web.go, web/job/*, and web/controller/* updated to
tgbot.*. Build, vet, and go test ./web/... pass.
* refactor(service): extract outbound/ subpackage
OutboundService (outbound.go) imports only neutral packages (config,
database, model, xray) and its production code is referenced by no core or
sibling service file — only by web/controller/xray_setting.go and
web/job/xray_traffic_job.go. Move it to web/service/outbound/ (package
outbound); no core qualification needed inside. Callers updated to outbound.*.
The one coupling was a tiny pure test helper, outboundsContainTag, used by
both outbound.go and the core outbound_subscription_test.go; it now has a
small copy in that test file rather than being shared across the boundary.
Build, vet, and go test ./web/... pass.
* refactor(util): move wireguard into its own subpackage
util/wireguard.go was the lone file of the root `util` package (24 lines,
one exported func GenerateWireguardKeypair), while every other util concern
lives in a focused subpackage (util/common, util/crypto, util/netsafe, ...).
Move it to util/wireguard/ (package wireguard) for consistency; its only
importer, web/service/integration/warp.go, is updated. The root `util`
package no longer exists.
* refactor(sub): drop redundant sub prefix from filenames
Inside package sub the subXxx.go prefix just repeats the package name
(like client_*.go did inside service). Rename for consistency; content and
type names are unchanged:
subController.go -> controller.go
subService.go -> service.go
subClashService.go -> clash_service.go
subJsonService.go -> json_service.go
(+ matching _test.go files)
* refactor(controller): rename xui.go -> spa.go
XUIController serves the panel's single-page-app shell; spa.go names that
role plainly (the other controller files are domain-named). File rename only
— the type stays XUIController. api_docs_test.go keys route base paths by
filename, so its "xui.go" case is updated to "spa.go".
* refactor: move backend packages under internal/
Adopt the idiomatic Go application layout: the backend packages now live
under internal/ (a boundary the toolchain enforces), signalling private
implementation instead of a library-style flat root. No runtime behavior
changes — only import paths and a few build/config paths move.
Moved: config, database, logger, mtproto, sub, util, web, xray -> internal/.
main.go stays at the repo root and tools/openapigen stays under tools/ (both
still import internal/* because the internal rule keys off the module root).
The module path github.com/mhsanaei/3x-ui/v3 is unchanged; 149 .go files had
their import prefix rewritten to .../internal/<pkg>.
Couplings the Go compiler can't see, updated to the new layout:
- frontend i18n imports of web/translation (react.ts, setup.components.ts)
- vite outDir + eslint/tsconfig ignore globs -> internal/web/dist
- Dockerfile COPY paths for web/dist and web/translation
- locale.go os.DirFS("web") disk fallback -> "internal/web"
- .gitignore and ci.yml go:embed stub for internal/web/dist
- api_docs_test.go repo-root relative walk (one level deeper)
- tools/openapigen filesystem package paths; ApiTokenView repointed to the
web/service/panel subpackage and codegen regenerated (clears a stale
type the ci.yml codegen check was failing on)
Verified: go build/vet/test (all packages), and frontend typecheck, lint,
vitest (478 tests), and production build into internal/web/dist.
* fix(config): keep test runs from writing logs into the source tree
GetLogFolder() returns a CWD-relative "./log" on Windows. Under `go test`
the working directory is each package's own folder, so InitLogger (called by
tests in web/job, web/service, xray, web/websocket) created stray log/
directories scattered through the source tree (e.g. internal/web/job/log/).
Redirect to a shared temp folder when testing.Testing() reports a test run.
Production behavior is unchanged: Windows still uses ./log next to the binary
and Linux /var/log/x-ui. The log files were always gitignored (*.log) and
never committed; this just stops the noise at the source.
* docs: move subscription-template guide out of root into docs/
sub_templates/ was a top-level folder holding only a README and no actual
templates (3x-ui ships none by design), referenced nowhere and unlinked from
any doc — it read like an empty placeholder cluttering the repo root.
Move the guide to docs/custom-subscription-templates.md (a proper docs home),
reword its intro to read as documentation rather than a folder note, link it
from the Features list in README.md, and drop the empty sub_templates/ folder.
* fix: update stale web/ path references after the internal/ move
The internal/ migration rewrote Go import paths but left some references to
the old top-level layout in docs, comments, and a few runtime disk paths.
Functional (dev-mode only): the disk-serving fallbacks that read the Vite
build from disk when running from source still pointed at web/dist/, which
moved to internal/web/dist/ — so `os.DirFS`/`os.Stat`/`os.ReadFile` in
internal/web/web.go and internal/sub/{sub,controller}.go are corrected.
Production was unaffected (it serves the embedded FS; verified by the Docker
build), but `go run` with a live frontend build silently fell back to embed.
Docs/comments: frontend/README.md, CONTRIBUTING.md, the claude-issue-bot and
release workflows, the openapigen -root help text, and assorted Go comments
now reference internal/web, internal/database, internal/sub, internal/xray,
etc. Package-name mentions (the "web" package), root paths (main.go,
frontend/, install scripts, /etc/x-ui), routes (/panel/api/xray), and the
historical "web/assets no longer exists" note were intentionally left as-is.
* refactor(web): remove the legacy /xui -> /panel redirect middleware
RedirectMiddleware existed only for backward compatibility with the old
`/xui` URL scheme (301-redirecting /xui and /xui/API to /panel and
/panel/api). That cutover was long ago, so drop the middleware, its
registration in initRouter, and the now-inaccurate "URL redirection"
mention in the middleware package doc. Old /xui URLs now 404 like any other
unknown path. HTTPS auto-redirect and auth redirects are unrelated and stay.
* build: fix .dockerignore for internal/ layout and exclude runtime dir
- web/dist -> internal/web/dist: the embedded frontend moved under internal/,
so the stale exclude no longer matched and the locally-built dist could be
sent to the build context (the frontend stage rebuilds it fresh anyway).
- exclude x-ui/: the local runtime directory (SQLite db, geo .dat files, xray
binaries, certs — ~150MB) was being shipped into the build context for no
reason. Verified the pattern excludes only the directory and still keeps
x-ui.sh, which the Dockerfile copies to /usr/bin/x-ui.
629 lines
18 KiB
Go
629 lines
18 KiB
Go
// Package main is the entry point for the 3x-ui web panel application.
|
|
// It initializes the database, web server, and handles command-line operations for managing the panel.
|
|
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
_ "unsafe"
|
|
|
|
"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/sub"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/sys"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
|
|
|
|
"github.com/joho/godotenv"
|
|
"github.com/op/go-logging"
|
|
)
|
|
|
|
// runWebServer initializes and starts the web server for the 3x-ui panel.
|
|
func runWebServer() {
|
|
log.Printf("Starting %v %v", config.GetName(), config.GetVersion())
|
|
|
|
switch config.GetLogLevel() {
|
|
case config.Debug:
|
|
logger.InitLogger(logging.DEBUG)
|
|
case config.Info:
|
|
logger.InitLogger(logging.INFO)
|
|
case config.Notice:
|
|
logger.InitLogger(logging.NOTICE)
|
|
case config.Warning:
|
|
logger.InitLogger(logging.WARNING)
|
|
case config.Error:
|
|
logger.InitLogger(logging.ERROR)
|
|
default:
|
|
log.Fatalf("Unknown log level: %v", config.GetLogLevel())
|
|
}
|
|
|
|
godotenv.Load()
|
|
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
log.Fatalf("Error initializing database: %v", err)
|
|
}
|
|
|
|
var server *web.Server
|
|
server = web.NewServer()
|
|
global.SetWebServer(server)
|
|
err = server.Start()
|
|
if err != nil {
|
|
log.Fatalf("Error starting web server: %v", err)
|
|
return
|
|
}
|
|
|
|
var subServer *sub.Server
|
|
sub.SetDistFS(web.EmbeddedDist())
|
|
service.RegisterSubLinkProvider(sub.NewLinkProvider())
|
|
subServer = sub.NewServer()
|
|
global.SetSubServer(subServer)
|
|
err = subServer.Start()
|
|
if err != nil {
|
|
log.Fatalf("Error starting sub server: %v", err)
|
|
return
|
|
}
|
|
|
|
sigCh := make(chan os.Signal, 1)
|
|
// Trap shutdown signals
|
|
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, sys.SIGUSR1, os.Interrupt)
|
|
global.SetRestartHook(func() {
|
|
select {
|
|
case sigCh <- syscall.SIGHUP:
|
|
default:
|
|
}
|
|
})
|
|
for {
|
|
sig := <-sigCh
|
|
|
|
switch sig {
|
|
case syscall.SIGHUP:
|
|
logger.Info("Received SIGHUP signal. Restarting servers...")
|
|
|
|
err := server.StopPanelOnly()
|
|
if err != nil {
|
|
logger.Debug("Error stopping web server:", err)
|
|
}
|
|
err = subServer.Stop()
|
|
if err != nil {
|
|
logger.Debug("Error stopping sub server:", err)
|
|
}
|
|
|
|
server = web.NewServer()
|
|
global.SetWebServer(server)
|
|
err = server.StartPanelOnly()
|
|
if err != nil {
|
|
log.Fatalf("Error restarting web server: %v", err)
|
|
return
|
|
}
|
|
log.Println("Web server restarted successfully.")
|
|
|
|
sub.SetDistFS(web.EmbeddedDist())
|
|
subServer = sub.NewServer()
|
|
global.SetSubServer(subServer)
|
|
err = subServer.Start()
|
|
if err != nil {
|
|
log.Fatalf("Error restarting sub server: %v", err)
|
|
return
|
|
}
|
|
log.Println("Sub server restarted successfully.")
|
|
case sys.SIGUSR1:
|
|
logger.Info("Received USR1 signal, restarting xray-core...")
|
|
err := server.RestartXray()
|
|
if err != nil {
|
|
logger.Error("Failed to restart xray-core:", err)
|
|
}
|
|
|
|
default:
|
|
// --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown ---
|
|
tgbot.StopBot()
|
|
// ------------------------------------------------------------
|
|
|
|
server.Stop()
|
|
subServer.Stop()
|
|
log.Println("Shutting down servers.")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// resetSetting resets all panel settings to their default values.
|
|
func resetSetting() error {
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
fmt.Println("Failed to initialize database:", err)
|
|
return err
|
|
}
|
|
|
|
settingService := service.SettingService{}
|
|
err = settingService.ResetSettings()
|
|
if err != nil {
|
|
fmt.Println("Failed to reset settings:", err)
|
|
return err
|
|
} else {
|
|
fmt.Println("Settings successfully reset.")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// showSetting displays the current panel settings if show is true.
|
|
func showSetting(show bool) {
|
|
if show {
|
|
settingService := service.SettingService{}
|
|
port, err := settingService.GetPort()
|
|
if err != nil {
|
|
fmt.Println("get current port failed, error info:", err)
|
|
}
|
|
|
|
webBasePath, err := settingService.GetBasePath()
|
|
if err != nil {
|
|
fmt.Println("get webBasePath failed, error info:", err)
|
|
}
|
|
|
|
certFile, err := settingService.GetCertFile()
|
|
if err != nil {
|
|
fmt.Println("get cert file failed, error info:", err)
|
|
}
|
|
keyFile, err := settingService.GetKeyFile()
|
|
if err != nil {
|
|
fmt.Println("get key file failed, error info:", err)
|
|
}
|
|
|
|
userService := panel.UserService{}
|
|
userModel, err := userService.GetFirstUser()
|
|
if err != nil {
|
|
fmt.Println("get current user info failed, error info:", err)
|
|
}
|
|
|
|
if userModel.Username == "" || userModel.Password == "" {
|
|
fmt.Println("current username or password is empty")
|
|
}
|
|
|
|
fmt.Println("current panel settings as follows:")
|
|
if certFile == "" || keyFile == "" {
|
|
fmt.Println("Warning: Panel is not secure with SSL")
|
|
} else {
|
|
fmt.Println("Panel is secure with SSL")
|
|
}
|
|
|
|
hasDefaultCredential := func() bool {
|
|
return userModel.Username == "admin" && crypto.CheckPasswordHash(userModel.Password, "admin")
|
|
}()
|
|
|
|
fmt.Println("hasDefaultCredential:", hasDefaultCredential)
|
|
fmt.Println("port:", port)
|
|
fmt.Println("webBasePath:", webBasePath)
|
|
}
|
|
}
|
|
|
|
// updateTgbotEnableSts enables or disables the Telegram bot notifications based on the status parameter.
|
|
func updateTgbotEnableSts(status bool) {
|
|
settingService := service.SettingService{}
|
|
currentTgSts, err := settingService.GetTgbotEnabled()
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
logger.Infof("current enabletgbot status[%v],need update to status[%v]", currentTgSts, status)
|
|
if currentTgSts != status {
|
|
err := settingService.SetTgbotEnabled(status)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
} else {
|
|
logger.Infof("SetTgbotEnabled[%v] success", status)
|
|
}
|
|
}
|
|
}
|
|
|
|
// updateTgbotSetting updates Telegram bot settings including token, chat ID, and runtime schedule.
|
|
func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime string) {
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
fmt.Println("Error initializing database:", err)
|
|
return
|
|
}
|
|
|
|
settingService := service.SettingService{}
|
|
|
|
if tgBotToken != "" {
|
|
err := settingService.SetTgBotToken(tgBotToken)
|
|
if err != nil {
|
|
fmt.Printf("Error setting Telegram bot token: %v\n", err)
|
|
return
|
|
}
|
|
logger.Info("Successfully updated Telegram bot token.")
|
|
}
|
|
|
|
if tgBotRuntime != "" {
|
|
err := settingService.SetTgbotRuntime(tgBotRuntime)
|
|
if err != nil {
|
|
fmt.Printf("Error setting Telegram bot runtime: %v\n", err)
|
|
return
|
|
}
|
|
logger.Infof("Successfully updated Telegram bot runtime to [%s].", tgBotRuntime)
|
|
}
|
|
|
|
if tgBotChatid != "" {
|
|
err := settingService.SetTgBotChatId(tgBotChatid)
|
|
if err != nil {
|
|
fmt.Printf("Error setting Telegram bot chat ID: %v\n", err)
|
|
return
|
|
}
|
|
logger.Info("Successfully updated Telegram bot chat ID.")
|
|
}
|
|
}
|
|
|
|
// updateSetting updates various panel settings including port, credentials, base path, listen IP, and two-factor authentication.
|
|
func updateSetting(port int, username string, password string, webBasePath string, listenIP string, resetTwoFactor bool) error {
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
fmt.Println("Database initialization failed:", err)
|
|
return err
|
|
}
|
|
|
|
settingService := service.SettingService{}
|
|
userService := panel.UserService{}
|
|
|
|
if port > 0 {
|
|
err := settingService.SetPort(port)
|
|
if err != nil {
|
|
fmt.Println("Failed to set port:", err)
|
|
} else {
|
|
fmt.Printf("Port set successfully: %v\n", port)
|
|
}
|
|
}
|
|
|
|
if username != "" || password != "" {
|
|
err := userService.UpdateFirstUser(username, password)
|
|
if err != nil {
|
|
fmt.Println("Failed to update username and password:", err)
|
|
} else {
|
|
fmt.Println("Username and password updated successfully")
|
|
}
|
|
}
|
|
|
|
if webBasePath != "" {
|
|
err := settingService.SetBasePath(webBasePath)
|
|
if err != nil {
|
|
fmt.Println("Failed to set base URI path:", err)
|
|
} else {
|
|
fmt.Println("Base URI path set successfully")
|
|
}
|
|
}
|
|
|
|
if resetTwoFactor {
|
|
err := settingService.SetTwoFactorEnable(false)
|
|
|
|
if err != nil {
|
|
fmt.Println("Failed to reset two-factor authentication:", err)
|
|
} else {
|
|
settingService.SetTwoFactorToken("")
|
|
fmt.Println("Two-factor authentication reset successfully")
|
|
}
|
|
}
|
|
|
|
if listenIP != "" {
|
|
err := settingService.SetListen(listenIP)
|
|
if err != nil {
|
|
fmt.Println("Failed to set listen IP:", err)
|
|
} else {
|
|
fmt.Printf("listen %v set successfully", listenIP)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// updateCert updates the SSL certificate files for the panel.
|
|
func updateCert(publicKey string, privateKey string) {
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
|
|
if (privateKey != "" && publicKey != "") || (privateKey == "" && publicKey == "") {
|
|
settingService := service.SettingService{}
|
|
err = settingService.SetCertFile(publicKey)
|
|
if err != nil {
|
|
fmt.Println("set certificate public key failed:", err)
|
|
} else {
|
|
fmt.Println("set certificate public key success")
|
|
}
|
|
|
|
err = settingService.SetKeyFile(privateKey)
|
|
if err != nil {
|
|
fmt.Println("set certificate private key failed:", err)
|
|
} else {
|
|
fmt.Println("set certificate private key success")
|
|
}
|
|
|
|
err = settingService.SetSubCertFile(publicKey)
|
|
if err != nil {
|
|
fmt.Println("set certificate for subscription public key failed:", err)
|
|
} else {
|
|
fmt.Println("set certificate for subscription public key success")
|
|
}
|
|
|
|
err = settingService.SetSubKeyFile(privateKey)
|
|
if err != nil {
|
|
fmt.Println("set certificate for subscription private key failed:", err)
|
|
} else {
|
|
fmt.Println("set certificate for subscription private key success")
|
|
}
|
|
} else {
|
|
fmt.Println("both public and private key should be entered.")
|
|
}
|
|
}
|
|
|
|
// GetCertificate displays the current SSL certificate settings if getCert is true.
|
|
func GetCertificate(getCert bool) {
|
|
if getCert {
|
|
settingService := service.SettingService{}
|
|
certFile, err := settingService.GetCertFile()
|
|
if err != nil {
|
|
fmt.Println("get cert file failed, error info:", err)
|
|
}
|
|
keyFile, err := settingService.GetKeyFile()
|
|
if err != nil {
|
|
fmt.Println("get key file failed, error info:", err)
|
|
}
|
|
|
|
fmt.Println("cert:", certFile)
|
|
fmt.Println("key:", keyFile)
|
|
}
|
|
}
|
|
|
|
// GetListenIP displays the current panel listen IP address if getListen is true.
|
|
func GetListenIP(getListen bool) {
|
|
if getListen {
|
|
|
|
settingService := service.SettingService{}
|
|
ListenIP, err := settingService.GetListen()
|
|
if err != nil {
|
|
log.Printf("Failed to retrieve listen IP: %v", err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("listenIP:", ListenIP)
|
|
}
|
|
}
|
|
|
|
func GetApiToken(getApiToken bool) {
|
|
if !getApiToken {
|
|
return
|
|
}
|
|
apiTokenService := panel.ApiTokenService{}
|
|
tokens, err := apiTokenService.List()
|
|
if err != nil {
|
|
fmt.Println("get apiToken failed, error info:", err)
|
|
return
|
|
}
|
|
if len(tokens) > 0 {
|
|
fmt.Println("apiToken:", tokens[0].Token)
|
|
return
|
|
}
|
|
created, err := apiTokenService.Create("install")
|
|
if err != nil {
|
|
fmt.Println("create apiToken failed, error info:", err)
|
|
return
|
|
}
|
|
fmt.Println("apiToken:", created.Token)
|
|
}
|
|
|
|
// migrateDb performs database migration operations for the 3x-ui panel.
|
|
func migrateDb() {
|
|
inboundService := service.InboundService{}
|
|
|
|
err := database.InitDB(config.GetDBPath())
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println("Start migrating database...")
|
|
inboundService.MigrateDB()
|
|
fmt.Println("Migration done!")
|
|
}
|
|
|
|
// loadServiceEnvFile loads the systemd EnvironmentFile so CLI subcommands like
|
|
// "x-ui setting" hit the same database backend as the panel. godotenv.Load does
|
|
// not override variables already in the environment, so it is a no-op for the
|
|
// systemd-managed service.
|
|
func loadServiceEnvFile() {
|
|
for _, path := range config.GetEnvFilePaths() {
|
|
if _, err := os.Stat(path); err != nil {
|
|
continue
|
|
}
|
|
if err := godotenv.Load(path); err != nil {
|
|
log.Printf("warning: failed to load env file %s: %v", path, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// main is the entry point of the 3x-ui application.
|
|
// It parses command-line arguments to run the web server, migrate database, or update settings.
|
|
func main() {
|
|
loadServiceEnvFile()
|
|
|
|
if len(os.Args) < 2 {
|
|
runWebServer()
|
|
return
|
|
}
|
|
|
|
var showVersion bool
|
|
flag.BoolVar(&showVersion, "v", false, "show version")
|
|
|
|
runCmd := flag.NewFlagSet("run", flag.ExitOnError)
|
|
|
|
migrateDbCmd := flag.NewFlagSet("migrate-db", flag.ExitOnError)
|
|
var migrateDsn string
|
|
var migrateSrc string
|
|
var migrateDump string
|
|
var migrateRestore string
|
|
var migrateOut string
|
|
migrateDbCmd.StringVar(&migrateDsn, "dsn", "", "Destination PostgreSQL DSN (postgres://user:pass@host:port/db?sslmode=disable)")
|
|
migrateDbCmd.StringVar(&migrateSrc, "src", "", "Source SQLite file (defaults to the configured x-ui.db)")
|
|
migrateDbCmd.StringVar(&migrateDump, "dump", "", "Write a portable SQL text dump of --src to this file (.db -> .dump)")
|
|
migrateDbCmd.StringVar(&migrateRestore, "restore", "", "Rebuild a SQLite database from this SQL text dump (.dump -> .db); requires --out")
|
|
migrateDbCmd.StringVar(&migrateOut, "out", "", "Destination SQLite file for --restore (must not already exist)")
|
|
|
|
settingCmd := flag.NewFlagSet("setting", flag.ExitOnError)
|
|
var port int
|
|
var username string
|
|
var password string
|
|
var webBasePath string
|
|
var listenIP string
|
|
var getListen bool
|
|
var webCertFile string
|
|
var webKeyFile string
|
|
var tgbottoken string
|
|
var tgbotchatid string
|
|
var enabletgbot bool
|
|
var tgbotRuntime string
|
|
var reset bool
|
|
var show bool
|
|
var getCert bool
|
|
var getApiToken bool
|
|
var resetTwoFactor bool
|
|
settingCmd.BoolVar(&reset, "reset", false, "Reset all settings")
|
|
settingCmd.BoolVar(&show, "show", false, "Display current settings")
|
|
settingCmd.IntVar(&port, "port", 0, "Set panel port number")
|
|
settingCmd.StringVar(&username, "username", "", "Set login username")
|
|
settingCmd.StringVar(&password, "password", "", "Set login password")
|
|
settingCmd.StringVar(&webBasePath, "webBasePath", "", "Set base path for Panel")
|
|
settingCmd.StringVar(&listenIP, "listenIP", "", "set panel listenIP IP")
|
|
settingCmd.BoolVar(&resetTwoFactor, "resetTwoFactor", false, "Reset two-factor authentication settings")
|
|
settingCmd.BoolVar(&getListen, "getListen", false, "Display current panel listenIP IP")
|
|
settingCmd.BoolVar(&getCert, "getCert", false, "Display current certificate settings")
|
|
settingCmd.BoolVar(&getApiToken, "getApiToken", false, "Display current API token")
|
|
settingCmd.StringVar(&webCertFile, "webCert", "", "Set path to public key file for panel")
|
|
settingCmd.StringVar(&webKeyFile, "webCertKey", "", "Set path to private key file for panel")
|
|
settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "Set token for Telegram bot")
|
|
settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "Set cron time for Telegram bot notifications")
|
|
settingCmd.StringVar(&tgbotchatid, "tgbotchatid", "", "Set chat ID for Telegram bot notifications")
|
|
settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "Enable notifications via Telegram bot")
|
|
|
|
oldUsage := flag.Usage
|
|
flag.Usage = func() {
|
|
oldUsage()
|
|
fmt.Println()
|
|
fmt.Println("Commands:")
|
|
fmt.Println(" run run web panel")
|
|
fmt.Println(" migrate migrate form other/old x-ui")
|
|
fmt.Println(" migrate-db SQLite <-> .dump (--dump/--restore) or copy into PostgreSQL (--dsn)")
|
|
fmt.Println(" setting set settings")
|
|
}
|
|
|
|
flag.Parse()
|
|
if showVersion {
|
|
fmt.Println(config.GetVersion())
|
|
return
|
|
}
|
|
|
|
switch os.Args[1] {
|
|
case "run":
|
|
err := runCmd.Parse(os.Args[2:])
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
runWebServer()
|
|
case "migrate":
|
|
migrateDb()
|
|
case "migrate-db":
|
|
if err := migrateDbCmd.Parse(os.Args[2:]); err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
src := migrateSrc
|
|
if src == "" {
|
|
src = config.GetDBPath()
|
|
}
|
|
switch {
|
|
case migrateDump != "":
|
|
if err := database.DumpSQLite(src, migrateDump); err != nil {
|
|
fmt.Println("dump failed:", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Dumped %s -> %s\n", src, migrateDump)
|
|
case migrateRestore != "":
|
|
if migrateOut == "" {
|
|
fmt.Println("--out is required when using --restore: the destination .db path (must not exist)")
|
|
return
|
|
}
|
|
if err := database.RestoreSQLite(migrateRestore, migrateOut); err != nil {
|
|
fmt.Println("restore failed:", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Restored %s -> %s\n", migrateRestore, migrateOut)
|
|
case migrateDsn != "":
|
|
if err := database.MigrateData(src, migrateDsn); err != nil {
|
|
fmt.Println("migration failed:", err)
|
|
os.Exit(1)
|
|
}
|
|
default:
|
|
fmt.Println("nothing to do: pass --dump <file>, --restore <file> --out <db>, or --dsn <postgres-dsn>")
|
|
}
|
|
case "setting":
|
|
err := settingCmd.Parse(os.Args[2:])
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
if reset {
|
|
if err = resetSetting(); err != nil {
|
|
return
|
|
}
|
|
} else {
|
|
if err = updateSetting(port, username, password, webBasePath, listenIP, resetTwoFactor); err != nil {
|
|
return
|
|
}
|
|
}
|
|
if show {
|
|
showSetting(show)
|
|
}
|
|
if getListen {
|
|
GetListenIP(getListen)
|
|
}
|
|
if getCert {
|
|
GetCertificate(getCert)
|
|
}
|
|
if getApiToken {
|
|
GetApiToken(getApiToken)
|
|
}
|
|
if (tgbottoken != "") || (tgbotchatid != "") || (tgbotRuntime != "") {
|
|
updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime)
|
|
}
|
|
if enabletgbot {
|
|
updateTgbotEnableSts(enabletgbot)
|
|
}
|
|
case "cert":
|
|
err := settingCmd.Parse(os.Args[2:])
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
if reset {
|
|
updateCert("", "")
|
|
} else {
|
|
updateCert(webCertFile, webKeyFile)
|
|
}
|
|
default:
|
|
fmt.Println("Invalid subcommands")
|
|
fmt.Println()
|
|
runCmd.Usage()
|
|
fmt.Println()
|
|
settingCmd.Usage()
|
|
}
|
|
}
|