|
| 1 | +# 3X-UI Development Guide |
| 2 | + |
| 3 | +## Project Overview |
| 4 | +3X-UI is a web-based control panel for managing Xray-core servers. It's a Go application using Gin web framework with embedded static assets and SQLite database. The panel manages VPN/proxy inbounds, monitors traffic, and provides Telegram bot integration. |
| 5 | + |
| 6 | +## Architecture |
| 7 | + |
| 8 | +### Core Components |
| 9 | +- **main.go**: Entry point that initializes database, web server, and subscription server. Handles graceful shutdown via SIGHUP/SIGTERM signals |
| 10 | +- **web/**: Primary web server with Gin router, HTML templates, and static assets embedded via `//go:embed` |
| 11 | +- **xray/**: Xray-core process management and API communication for traffic monitoring |
| 12 | +- **database/**: GORM-based SQLite database with models in `database/model/` |
| 13 | +- **sub/**: Subscription server running alongside main web server (separate port) |
| 14 | +- **web/service/**: Business logic layer containing InboundService, SettingService, TgBot, etc. |
| 15 | +- **web/controller/**: HTTP handlers using Gin context (`*gin.Context`) |
| 16 | +- **web/job/**: Cron-based background jobs for traffic monitoring, CPU checks, LDAP sync |
| 17 | + |
| 18 | +### Key Architectural Patterns |
| 19 | +1. **Embedded Resources**: All web assets (HTML, CSS, JS, translations) are embedded at compile time using `embed.FS`: |
| 20 | + - `web/assets` → `assetsFS` |
| 21 | + - `web/html` → `htmlFS` |
| 22 | + - `web/translation` → `i18nFS` |
| 23 | + |
| 24 | +2. **Dual Server Design**: Main web panel + subscription server run concurrently, managed by `web/global` package |
| 25 | + |
| 26 | +3. **Xray Integration**: Panel generates `config.json` for Xray binary, communicates via gRPC API for real-time traffic stats |
| 27 | + |
| 28 | +4. **Signal-Based Restart**: SIGHUP triggers graceful restart. **Critical**: Always call `service.StopBot()` before restart to prevent Telegram bot 409 conflicts |
| 29 | + |
| 30 | +5. **Database Seeders**: Uses `HistoryOfSeeders` model to track one-time migrations (e.g., password bcrypt migration) |
| 31 | + |
| 32 | +## Development Workflows |
| 33 | + |
| 34 | +### Building & Running |
| 35 | +```bash |
| 36 | +# Build (creates bin/3x-ui.exe) |
| 37 | +go run tasks.json → "go: build" task |
| 38 | + |
| 39 | +# Run with debug logging |
| 40 | +XUI_DEBUG=true go run ./main.go |
| 41 | +# Or use task: "go: run" |
| 42 | + |
| 43 | +# Test |
| 44 | +go test ./... |
| 45 | +``` |
| 46 | + |
| 47 | +### Command-Line Operations |
| 48 | +The main.go accepts flags for admin tasks: |
| 49 | +- `-reset` - Reset all panel settings to defaults |
| 50 | +- `-show` - Display current settings (port, paths) |
| 51 | +- Use these by running the binary directly, not via web interface |
| 52 | + |
| 53 | +### Database Management |
| 54 | +- DB path: Configured via `config.GetDBPath()`, typically `/etc/x-ui/x-ui.db` |
| 55 | +- Models: Located in `database/model/model.go` - Auto-migrated on startup |
| 56 | +- Seeders: Use `HistoryOfSeeders` to prevent re-running migrations |
| 57 | +- Default credentials: admin/admin (hashed with bcrypt) |
| 58 | + |
| 59 | +### Telegram Bot Development |
| 60 | +- Bot instance in `web/service/tgbot.go` (3700+ lines) |
| 61 | +- Uses `telego` library with long polling |
| 62 | +- **Critical Pattern**: Must call `service.StopBot()` before any server restart to prevent 409 bot conflicts |
| 63 | +- Bot handlers use `telegohandler.BotHandler` for routing |
| 64 | +- i18n via embedded `i18nFS` passed to bot startup |
| 65 | + |
| 66 | +## Code Conventions |
| 67 | + |
| 68 | +### Service Layer Pattern |
| 69 | +Services inject dependencies (like xray.XrayAPI) and operate on GORM models: |
| 70 | +```go |
| 71 | +type InboundService struct { |
| 72 | + xrayApi xray.XrayAPI |
| 73 | +} |
| 74 | + |
| 75 | +func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { |
| 76 | + // Business logic here |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +### Controller Pattern |
| 81 | +Controllers use Gin context and inherit from BaseController: |
| 82 | +```go |
| 83 | +func (a *InboundController) getInbounds(c *gin.Context) { |
| 84 | + // Use I18nWeb(c, "key") for translations |
| 85 | + // Check auth via checkLogin middleware |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +### Configuration Management |
| 90 | +- Environment vars: `XUI_DEBUG`, `XUI_LOG_LEVEL`, `XUI_MAIN_FOLDER` |
| 91 | +- Config embedded files: `config/version`, `config/name` |
| 92 | +- Use `config.GetLogLevel()`, `config.GetDBPath()` helpers |
| 93 | + |
| 94 | +### Internationalization |
| 95 | +- Translation files: `web/translation/translate.*.toml` |
| 96 | +- Access via `I18nWeb(c, "pages.login.loginAgain")` in controllers |
| 97 | +- Use `locale.I18nType` enum (Web, Api, etc.) |
| 98 | + |
| 99 | +## External Dependencies & Integration |
| 100 | + |
| 101 | +### Xray-core |
| 102 | +- Binary management: Download platform-specific binary (`xray-{os}-{arch}`) to bin folder |
| 103 | +- Config generation: Panel creates `config.json` dynamically from inbound/outbound settings |
| 104 | +- Process control: Start/stop via `xray/process.go` |
| 105 | +- gRPC API: Real-time stats via `xray/api.go` using `google.golang.org/grpc` |
| 106 | + |
| 107 | +### Critical External Paths |
| 108 | +- Xray binary: `{bin_folder}/xray-{os}-{arch}` |
| 109 | +- Xray config: `{bin_folder}/config.json` |
| 110 | +- GeoIP/GeoSite: `{bin_folder}/geoip.dat`, `geosite.dat` |
| 111 | +- Logs: `{log_folder}/3xipl.log`, `3xipl-banned.log` |
| 112 | + |
| 113 | +### Job Scheduling |
| 114 | +Uses `robfig/cron/v3` for periodic tasks: |
| 115 | +- Traffic monitoring: `xray_traffic_job.go` |
| 116 | +- CPU alerts: `check_cpu_usage.go` |
| 117 | +- IP tracking: `check_client_ip_job.go` |
| 118 | +- LDAP sync: `ldap_sync_job.go` |
| 119 | + |
| 120 | +Jobs registered in `web/web.go` during server initialization |
| 121 | + |
| 122 | +## Deployment & Scripts |
| 123 | + |
| 124 | +### Installation Script Pattern |
| 125 | +Both `install.sh` and `x-ui.sh` follow these patterns: |
| 126 | +- Multi-distro support via `$release` variable (ubuntu, debian, centos, arch, etc.) |
| 127 | +- Port detection with `is_port_in_use()` using ss/netstat/lsof |
| 128 | +- Systemd service management with distro-specific unit files (`.service.debian`, `.service.arch`, `.service.rhel`) |
| 129 | + |
| 130 | +### Docker Build |
| 131 | +Multi-stage Dockerfile: |
| 132 | +1. **Builder**: CGO-enabled build, runs `DockerInit.sh` to download Xray binary |
| 133 | +2. **Final**: Alpine-based with fail2ban pre-configured |
| 134 | + |
| 135 | +### Key File Locations (Production) |
| 136 | +- Binary: `/usr/local/x-ui/` |
| 137 | +- Database: `/etc/x-ui/x-ui.db` |
| 138 | +- Logs: `/var/log/x-ui/` |
| 139 | +- Service: `/etc/systemd/system/x-ui.service.*` |
| 140 | + |
| 141 | +## Testing & Debugging |
| 142 | +- Set `XUI_DEBUG=true` for detailed logging |
| 143 | +- Check Xray process: `x-ui.sh` script provides menu for status/logs |
| 144 | +- Database inspection: Direct SQLite access to x-ui.db |
| 145 | +- Traffic debugging: Check `3xipl.log` for IP limit tracking |
| 146 | +- Telegram bot: Logs show bot initialization and command handling |
| 147 | + |
| 148 | +## Common Gotchas |
| 149 | +1. **Bot Restart**: Always stop Telegram bot before server restart to avoid 409 conflict |
| 150 | +2. **Embedded Assets**: Changes to HTML/CSS require recompilation (not hot-reload) |
| 151 | +3. **Password Migration**: Seeder system tracks bcrypt migration - check `HistoryOfSeeders` table |
| 152 | +4. **Port Binding**: Subscription server uses different port from main panel |
| 153 | +5. **Xray Binary**: Must match OS/arch exactly - managed by installer scripts |
| 154 | +6. **Session Management**: Uses `gin-contrib/sessions` with cookie store |
| 155 | +7. **IP Limitation**: Implements "last IP wins" - when client exceeds LimitIP, oldest connections are automatically disconnected via Xray API to allow newest IPs |
0 commit comments