Showing preview only (475K chars total). Download the full file or copy to clipboard to get everything.
Repository: alireza0/s-ui
Branch: main
Commit: 1ef0ffa60eb8
Files: 106
Total size: 448.7 KB
Directory structure:
gitextract_ttjhfz3g/
├── .dockerignore
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── feature_request.md
│ │ └── question-template.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── docker.yml
│ ├── release.yml
│ └── windows.yml
├── .gitignore
├── .gitmodules
├── CONTRIBUTING.md
├── Dockerfile
├── Dockerfile.frontend-artifact
├── LICENSE
├── README.md
├── api/
│ ├── apiHandler.go
│ ├── apiService.go
│ ├── apiV2Handler.go
│ ├── session.go
│ └── utils.go
├── app/
│ └── app.go
├── build.sh
├── cmd/
│ ├── admin.go
│ ├── cmd.go
│ ├── migration/
│ │ ├── 1_1.go
│ │ ├── 1_2.go
│ │ ├── 1_3.go
│ │ └── main.go
│ └── setting.go
├── config/
│ ├── config.go
│ ├── name
│ └── version
├── core/
│ ├── box.go
│ ├── endpoint.go
│ ├── log.go
│ ├── main.go
│ ├── outbound_check.go
│ ├── register.go
│ ├── register_naive.go
│ ├── register_naive_stub.go
│ ├── tracker_conn.go
│ └── tracker_stats.go
├── cronjob/
│ ├── WALCheckpointJob.go
│ ├── checkCoreJob.go
│ ├── cronJob.go
│ ├── delStatsJob.go
│ ├── depleteJob.go
│ └── statsJob.go
├── database/
│ ├── backup.go
│ ├── db.go
│ └── model/
│ ├── endpoints.go
│ ├── inbounds.go
│ ├── model.go
│ ├── outbounds.go
│ └── services.go
├── docker-build-test.sh
├── docker-compose.yml
├── entrypoint.sh
├── go.mod
├── go.sum
├── install.sh
├── logger/
│ └── logger.go
├── main.go
├── middleware/
│ └── domainValidator.go
├── network/
│ ├── auto_https_conn.go
│ └── auto_https_listener.go
├── runSUI.sh
├── s-ui.service
├── s-ui.sh
├── service/
│ ├── client.go
│ ├── config.go
│ ├── endpoints.go
│ ├── inbounds.go
│ ├── outbounds.go
│ ├── panel.go
│ ├── server.go
│ ├── services.go
│ ├── setting.go
│ ├── stats.go
│ ├── tls.go
│ ├── user.go
│ └── warp.go
├── sub/
│ ├── clashService.go
│ ├── jsonService.go
│ ├── linkService.go
│ ├── sub.go
│ ├── subHandler.go
│ └── subService.go
├── util/
│ ├── base64.go
│ ├── common/
│ │ ├── array.go
│ │ ├── err.go
│ │ └── random.go
│ ├── genLink.go
│ ├── linkToJson.go
│ ├── outJson.go
│ ├── subInfo.go
│ └── subToJson.go
├── web/
│ └── web.go
└── windows/
├── README.md
├── build-windows.bat
├── build-windows.ps1
├── install-windows.bat
├── s-ui-windows.bat
├── s-ui-windows.xml
└── uninstall-windows.bat
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
.DS_Store
dist/
release/
backup/
bin/
db/
sui
web/html
main
tmp
.sync*
*.tar.gz
frontend/node_modules
frontend/.vite
# local env files
.env.local
.env.*.local
# Log files
*.log*
.cache
# Editor directories and files
.idea
.vscode
================================================
FILE: .github/FUNDING.yml
================================================
github: alireza0
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/ISSUE_TEMPLATE/question-template.md
================================================
---
name: Question template
about: Ask if it is not clear that it is a bug
title: ''
labels: question
assignees: ''
---
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
================================================
FILE: .github/workflows/docker.yml
================================================
name: Docker Image CI
on:
push:
tags:
- "*"
workflow_dispatch:
jobs:
frontend-build:
runs-on: ubuntu-24.04
steps:
- name: Checkout repository
uses: actions/checkout@v6.0.2
with:
submodules: recursive
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: 24
- name: Install dependencies and build frontend
run: |
cd frontend
npm install
npm run build
- name: Upload frontend build artifact
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend/dist/
build:
needs: frontend-build
strategy:
fail-fast: false
matrix:
include:
- { platform: linux/amd64 }
- { platform: linux/386 }
- { platform: linux/arm64/v8 }
- { platform: linux/arm/v7 }
- { platform: linux/arm/v6 }
runs-on: ubuntu-24.04
steps:
- name: Checkout repository
uses: actions/checkout@v6.0.2
- name: Download frontend build artifact
uses: actions/download-artifact@v8
with:
name: frontend-dist
path: frontend_dist
- name: Prepare
run: |
platform="${{ matrix.platform }}"
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: |
alireza7/s-ui
ghcr.io/alireza0/s-ui
tags: |
type=ref,event=branch
type=ref,event=tag
type=pep440,pattern={{version}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Cache Docker layers
uses: actions/cache@v5
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ matrix.platform }}-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-${{ matrix.platform }}-
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Login to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: .
file: Dockerfile.frontend-artifact
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
tags: |
alireza7/s-ui
ghcr.io/alireza0/s-ui
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache,mode=max
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
- name: Export digest
run: |
mkdir -p ${{ runner.temp }}/digests
digest="${{ steps.build.outputs.digest }}"
echo "${digest#sha256:}" > "${{ runner.temp }}/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
merge:
needs: build
runs-on: ubuntu-24.04
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: ${{ runner.temp }}/digests
pattern: digests-*
merge-multiple: true
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Login to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: |
alireza7/s-ui
ghcr.io/alireza0/s-ui
tags: |
type=ref,event=branch
type=ref,event=tag
type=pep440,pattern={{version}}
- name: Create manifest list and push
env:
DOCKER_METADATA_OUTPUT_JSON: ${{ steps.meta.outputs.json }}
working-directory: ${{ runner.temp }}/digests
run: |
set -e
for img in alireza7/s-ui ghcr.io/alireza0/s-ui; do
TAGS_ARGS=$(echo "$DOCKER_METADATA_OUTPUT_JSON" | jq -cr --arg img "$img" '.tags | map(select(startswith($img))) | map("-t " + .) | join(" ")')
DIGEST_REFS=$(for f in *; do echo -n "${img}@sha256:$(cat "$f") "; done)
docker buildx imagetools create $TAGS_ARGS $DIGEST_REFS
done
================================================
FILE: .github/workflows/release.yml
================================================
name: Release S-UI
on:
workflow_dispatch:
release:
types: [published]
push:
branches:
- main
tags:
- "*"
paths:
- '.github/workflows/release.yml'
- 'frontend/**'
- '**.sh'
- '**.go'
- 'go.mod'
- 'go.sum'
- 's-ui.service'
env:
NODE_VERSION: "24"
CRONET_GO_VERSION: "cba7b9ac0399055aa49fbdc57c03c374f58e1597"
CRONET_GO_REPO: https://github.com/sagernet/cronet-go.git
BOOTLIN_BASE_URL: https://toolchains.bootlin.com/downloads/releases/toolchains
CHROMIUM_CACHE_KEY_SUFFIX: musl-cba7b9ac0399055aa49fbdc57c03c374f58e1597
jobs:
build-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout repository (frontend only)
uses: actions/checkout@v6.0.2
with:
submodules: recursive
fetch-depth: 1
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Build frontend
run: |
cd frontend
npm ci
npm run build
cd ..
- name: Upload frontend dist
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend/dist/
build-linux:
name: build-${{ matrix.platform }}
needs: build-frontend
strategy:
fail-fast: false
matrix:
include:
- { platform: amd64, arch: amd64, bootlin: x86-64, naive: true }
- { platform: arm64, arch: arm64, bootlin: aarch64, naive: true }
- { platform: armv7, arch: arm, goarm: "7", bootlin: armv7-eabihf, naive: true }
- { platform: armv6, arch: arm, goarm: "6", bootlin: armv6-eabihf, naive: true }
- { platform: armv5, arch: arm, goarm: "5", bootlin: armv5-eabi, naive: false }
- { platform: "386", arch: "386", bootlin: x86-i686, naive: true }
- { platform: s390x, arch: s390x, bootlin: s390x-z13, naive: false }
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6.0.2
- name: Download frontend dist
uses: actions/download-artifact@v8
with:
name: frontend-dist
path: web/html
- name: Setup Go
uses: actions/setup-go@v6
with:
cache: false
go-version-file: go.mod
# Naive platforms: use cronet toolchain only (no Bootlin).
- name: Clone cronet-go (cronet toolchain for naive)
if: matrix.naive
run: |
set -e
git init ~/cronet-go
git -C ~/cronet-go remote add origin ${{ env.CRONET_GO_REPO }}
git -C ~/cronet-go fetch --depth=1 origin "${{ env.CRONET_GO_VERSION }}"
git -C ~/cronet-go checkout FETCH_HEAD
git -C ~/cronet-go submodule update --init --recursive --depth=1
- name: Regenerate Debian keyring (cronet sysroot)
if: matrix.naive
run: |
set -e
rm -f ~/cronet-go/naiveproxy/src/build/linux/sysroot_scripts/keyring.gpg
cd ~/cronet-go
GPG_TTY=/dev/null ./naiveproxy/src/build/linux/sysroot_scripts/generate_keyring.sh
- name: Cache Chromium toolchain
if: matrix.naive
id: cache-chromium-toolchain
uses: actions/cache@v5
with:
path: |
~/cronet-go/naiveproxy/src/third_party/llvm-build/
~/cronet-go/naiveproxy/src/gn/out/
~/cronet-go/naiveproxy/src/chrome/build/pgo_profiles/
~/cronet-go/naiveproxy/src/out/sysroot-build/
key: chromium-toolchain-${{ matrix.platform }}-${{ env.CHROMIUM_CACHE_KEY_SUFFIX }}
- name: Build cronet lib and set toolchain env (CC, CXX, CGO_LDFLAGS, PATH)
if: matrix.naive
run: |
set -e
cd ~/cronet-go
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl download-toolchain
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl env | while IFS= read -r line; do
line="${line#export }"
[[ -z "$line" ]] && continue
echo "$line" >> $GITHUB_ENV
done
- name: Set Go build env (all platforms)
run: |
echo "CGO_ENABLED=1" >> $GITHUB_ENV
echo "GOOS=linux" >> $GITHUB_ENV
echo "GOARCH=${{ matrix.arch }}" >> $GITHUB_ENV
if [ -n "${{ matrix.goarm }}" ]; then echo "GOARM=${{ matrix.goarm }}" >> $GITHUB_ENV; fi
# Non-naive platforms only: Bootlin musl (armv5, s390x).
- name: Set up Bootlin musl (armv5, s390x)
if: ${{ matrix.naive != true }}
run: |
set -e
BOOTLIN_ARCH="${{ matrix.bootlin }}"
echo "Resolving Bootlin musl toolchain for arch=$BOOTLIN_ARCH (platform=${{ matrix.platform }})"
TARBALL_BASE="${{ env.BOOTLIN_BASE_URL }}/$BOOTLIN_ARCH/tarballs/"
TARBALL_URL=$(curl -fsSL "$TARBALL_BASE" | grep -oE "${BOOTLIN_ARCH}--musl--stable-[^\"]+\\.tar\\.xz" | sort -r | head -n1)
[ -z "$TARBALL_URL" ] && { echo "Failed to locate Bootlin musl toolchain for arch=$BOOTLIN_ARCH" >&2; exit 1; }
echo "Downloading: $TARBALL_URL"
cd /tmp
curl -fL -sS -o "$(basename "$TARBALL_URL")" "$TARBALL_BASE/$TARBALL_URL"
tar -xf "$(basename "$TARBALL_URL")"
TOOLCHAIN_DIR=$(find . -maxdepth 1 -type d -name "${BOOTLIN_ARCH}--musl--stable-*" | head -n1)
TOOLCHAIN_DIR="$(realpath "$TOOLCHAIN_DIR")"
BIN_DIR="$TOOLCHAIN_DIR/bin"
echo "PATH=$BIN_DIR:$PATH" >> $GITHUB_ENV
CC=$(find "$BIN_DIR" -maxdepth 1 \( -name '*-gcc.br_real' -o -name '*-gcc' \) -type f -executable 2>/dev/null | grep -v g++ | head -n1)
[ -z "$CC" ] && { echo "No gcc found in $BIN_DIR" >&2; exit 1; }
echo "CC=$(realpath "$CC")" >> $GITHUB_ENV
SYSROOT=""
F=$(find "$TOOLCHAIN_DIR" -name "libc-header-start.h" 2>/dev/null | head -1)
if [ -n "$F" ]; then SYSROOT=$(dirname "$(dirname "$(dirname "$(dirname "$F")")")"); fi
if [ -n "$SYSROOT" ] && [ -d "$SYSROOT" ]; then
echo "CGO_CFLAGS=--sysroot=$SYSROOT" >> $GITHUB_ENV
echo "CGO_LDFLAGS=--sysroot=$SYSROOT -static" >> $GITHUB_ENV
fi
- name: Build s-ui
run: |
set -e
BUILD_TAGS="with_quic,with_grpc,with_utls,with_acme,with_gvisor,badlinkname,tfogo_checklinkname0"
[ "${{ matrix.naive }}" = "true" ] && BUILD_TAGS="${BUILD_TAGS},with_naive_outbound,with_musl"
go build -ldflags="-w -s -checklinkname=0 -linkmode external -extldflags '-static'" -tags "$BUILD_TAGS" -o sui main.go
file sui
ldd sui 2>/dev/null || echo "Static binary confirmed"
mkdir s-ui
cp sui s-ui/
cp s-ui.service s-ui/
cp s-ui.sh s-ui/
- name: Package
run: tar -zcvf s-ui-linux-${{ matrix.platform }}.tar.gz s-ui
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: s-ui-linux-${{ matrix.platform }}
path: ./s-ui-linux-${{ matrix.platform }}.tar.gz
retention-days: 30
- name: Upload to Release
uses: svenstaro/upload-release-action@v2
if: |
(github.event_name == 'release' && github.event.action == 'published') ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref_name }}
file: s-ui-linux-${{ matrix.platform }}.tar.gz
asset_name: s-ui-linux-${{ matrix.platform }}.tar.gz
prerelease: true
overwrite: true
================================================
FILE: .github/workflows/windows.yml
================================================
name: Build S-UI for Windows
on:
workflow_dispatch:
release:
types: [published]
push:
branches:
- main
tags:
- "*"
paths:
- '.github/workflows/windows.yml'
- 'frontend/**'
- '**.go'
- 'go.mod'
- 'go.sum'
- 'windows/**'
env:
NODE_VERSION: "24"
TAGS: "with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego,badlinkname,tfogo_checklinkname0"
LIBCRONET_BASE_URL: "https://github.com/SagerNet/cronet-go/releases/latest/download"
jobs:
build-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6.0.2
with:
submodules: recursive
fetch-depth: 1
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
registry-url: 'https://registry.npmjs.org'
- name: Build frontend
run: |
cd frontend
npm install
npm run build
cd ..
- name: Upload frontend artifact
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend/dist
retention-days: 1
build-windows:
needs: build-frontend
name: build-windows-${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- { arch: amd64, runner: windows-latest, cgo: "1" }
- { arch: arm64, runner: ubuntu-latest, cgo: "0" }
runs-on: ${{ matrix.runner }}
steps:
- name: Checkout repository
uses: actions/checkout@v6.0.2
- name: Download frontend artifact
uses: actions/download-artifact@v8
with:
name: frontend-dist
path: web/html
- name: Setup Go
uses: actions/setup-go@v6
with:
cache: false
go-version-file: go.mod
- name: Install zip for Windows
if: matrix.arch == 'amd64'
shell: powershell
run: |
# Install Chocolatey if not available
if (!(Get-Command choco -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}
# Install zip
choco install zip -y
- name: Build s-ui
shell: bash
run: |
export CGO_ENABLED=${{ matrix.cgo }}
export GOOS=windows
export GOARCH=${{ matrix.arch }}
echo "Building for Windows ${{ matrix.arch }}"
go version
go env GOOS GOARCH
go build -ldflags="-w -s -checklinkname=0" -tags "${{ env.TAGS }}" -o sui.exe main.go
file sui.exe
mkdir s-ui-windows
cp sui.exe s-ui-windows/
cp -r windows/* s-ui-windows/
- name: Download libcronet-go
shell: bash
run: |
curl -qsL -o s-ui-windows/libcronet.dll ${{ env.LIBCRONET_BASE_URL }}/libcronet-windows-${{ matrix.arch }}.dll
- name: Package
shell: bash
run: |
zip -r "s-ui-windows-${{ matrix.arch }}.zip" s-ui-windows
- name: Upload files to Artifacts
uses: actions/upload-artifact@v7
with:
name: s-ui-windows-${{ matrix.arch }}
path: ./s-ui-windows-${{ matrix.arch }}.zip
retention-days: 30
- name: Upload to Release
uses: svenstaro/upload-release-action@v2
if: |
(github.event_name == 'release' && github.event.action == 'published') ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.ref }}
file: s-ui-windows-${{ matrix.arch }}.zip
asset_name: s-ui-windows-${{ matrix.arch }}.zip
prerelease: true
overwrite: true
================================================
FILE: .gitignore
================================================
.DS_Store
dist/
release/
backup/
bin/
db/
sui
web/html
main
tmp
.sync*
*.tar.gz
frontend/
# local env files
.env.local
.env.*.local
# Log files
*.log*
.cache
# Windows build artifacts
*.exe
*.zip
s-ui-windows/
sui-*.exe
sui-*.zip
windows/sui-*.exe
# Editor directories and files
.idea
.vscode
================================================
FILE: .gitmodules
================================================
[submodule "frontend"]
path = frontend
url = https://github.com/alireza0/s-ui-frontend
branch = main
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to S-UI
Thank you for your interest in contributing to S-UI. This document explains how to set up a development environment, follow project conventions, and submit changes. Your contributions help make the **multi-inbound-per-user** approach and the rest of the project better for everyone.
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [Development Environment Setup](#development-environment-setup)
- [Coding Conventions and Style Guide](#coding-conventions-and-style-guide)
- [Testing](#testing)
- [Features That Need Help](#features-that-need-help)
- [Pull Request Process](#pull-request-process)
- [Adding This Guide in Your Repository](#adding-this-guide-in-your-repository)
- [Reporting Bugs and Requesting Features](#reporting-bugs-and-requesting-features)
---
## Code of Conduct
Please be respectful and constructive when interacting with maintainers and other contributors. This project is for personal learning and communication; use it responsibly and legally.
---
## Development Environment Setup
### Prerequisites
- **Go**: 1.25 or later (see `go.mod` for the exact version).
- **Git**: For cloning and submodules.
- **C compiler**: Required for CGO (e.g. `gcc`, `musl-dev` on Alpine).
- **Node.js** (optional): Only if you plan to work on or rebuild the frontend. The repo can be run with pre-built frontend assets.
### Clone and Submodules
```bash
git clone https://github.com/alireza0/s-ui
cd s-ui
git submodule update --init --recursive
```
The **frontend** lives in a submodule. If you only work on the backend, you can use the existing `web/html` contents or build the frontend once (see below).
### Backend-Only Development (quickest)
1. Build and run with the provided script (builds backend and runs with debug + local DB):
```bash
./runSUI.sh
```
This runs `./build.sh` then `SUI_DB_FOLDER="db" SUI_DEBUG=true ./sui`.
2. Or build manually:
```bash
./build.sh
SUI_DB_FOLDER=db SUI_DEBUG=true ./sui
```
Default panel: **http://localhost:2095/app/** (user: `admin`, password: `admin` — change in production).
### Full Stack (Backend + Frontend)
1. **Frontend** (separate repo in submodule):
```bash
cd frontend
npm install
npm run build
cd ..
```
2. **Replace web assets and build backend**:
```bash
mkdir -p web/html
rm -rf web/html/*
cp -R frontend/dist/* web/html/
go build -ldflags "-w -s" -tags "with_quic,with_grpc,with_utls,with_acme,with_gvisor" -o sui main.go
```
3. Run:
```bash
SUI_DB_FOLDER=db SUI_DEBUG=true ./sui
```
### Build Tags
The backend is built with these tags for full functionality:
- `with_quic`, `with_grpc`, `with_utls`, `with_acme`, `with_gvisor`
Use the same tags when building locally if you need feature parity with releases.
### Environment Variables (development)
| Variable | Description | Example |
|----------------|--------------------------------|-----------|
| `SUI_DB_FOLDER`| Directory for SQLite DB files | `db` |
| `SUI_DEBUG` | Enable debug mode | `true` |
| `SUI_LOG_LEVEL`| Log level | `debug` |
| `SUI_BIN_FOLDER` | Directory for binaries | `bin` |
### Docker (optional)
```bash
git clone https://github.com/alireza0/s-ui
cd s-ui
git submodule update --init --recursive
docker build -t s-ui .
# or: docker compose up -d
```
---
## Coding Conventions and Style Guide
### General
- Write clear, maintainable code. Prefer small, focused functions and packages.
- Comment non-obvious logic and public APIs.
- Handle errors explicitly; avoid ignoring `err` unless intentional.
### Go Style
- Follow **standard Go style** and **[Effective Go](https://go.dev/doc/effective_go)**.
- Run **gofmt** (or **goimports**) before committing:
```bash
gofmt -w .
# or: goimports -w .
```
- Use **camelCase** for unexported names and **PascalCase** for exported names.
- Keep package names short and lowercase (e.g. `api`, `service`, `util`).
- Group imports: standard library, then third-party, then project imports (as in existing files).
### Project Structure Conventions
- **`api/`**: HTTP handlers and API routing (e.g. `apiHandler.go`, `apiV2Handler.go`).
- **`service/`**: Business logic and panel/core operations.
- **`database/model/`**: GORM models and DB entities.
- **`util/`**: Shared utilities (e.g. link/sub conversion, JSON).
- **`core/`**: sing-box integration and core runtime.
- **`sub/`**: Subscription (link/json) handling.
When adding new features, place code in the appropriate layer (handler → service → model/util) and avoid circular dependencies.
### Naming and Patterns
- Handlers: suffix `Handler` (e.g. `APIHandler`, `APIv2Handler`).
- Services: suffix `Service` or use package name (e.g. `ApiService`, `LinkService`).
- Models: clear struct names with JSON/gorm tags (see `database/model/`).
---
## Testing
### Current State
- The project does not yet have a formal test suite (no `*_test.go` files in the repo).
- CI currently focuses on **builds** (e.g. `release.yml`) rather than automated tests.
### What You Can Do Now
1. **Build verification**: Before submitting a PR, ensure the project builds:
```bash
go build -ldflags "-w -s" -tags "with_quic,with_grpc,with_utls,with_acme,with_gvisor" -o sui main.go
```
2. **Manual testing**: Run with `./runSUI.sh`, test the changed area (panel, API, subscription, etc.).
3. **Future tests**: Contributions that add **unit tests** (e.g. for `util/`, `service/`, or API handlers) or **integration tests** are very welcome. Prefer the standard library `testing` package and table-driven tests where appropriate.
### Running the Linter (optional)
```bash
go vet ./...
# Optional: staticcheck, golangci-lint, etc.
```
---
## Features That Need Help
Community help is especially valuable in these areas. Check the [Issues](https://github.com/alireza0/s-ui/issues) for current tasks and ideas.
### High-Value Areas
- **Multi-inbound per user**: Core differentiator of S-UI; improvements to UX, docs, and robustness are welcome.
- **API (v1 and v2)**: Completeness, consistency, and documentation (see [API Documentation](https://github.com/alireza0/s-ui/wiki/API-Documentation)).
- **Subscription service**: Link conversion, JSON subscription, and info endpoints (`sub/`, `util/`).
- **Testing**: Adding unit and integration tests for critical paths.
- **Documentation**: User docs, API examples, and contribution docs (like this file).
- **Platform support**: macOS is experimental; Windows and Linux improvements are welcome (see `windows/` and `.github/workflows/`).
### How to Find Tasks
- **Good first issue**: Look for issues labeled `good first issue` or `help wanted`.
- **Feature requests**: [Feature request template](.github/ISSUE_TEMPLATE/feature_request.md).
- **Bugs**: [Bug report template](.github/ISSUE_TEMPLATE/bug_report.md).
If you want to work on a larger feature, open an issue first to discuss approach and avoid duplicate work.
---
## Pull Request Process
1. **Fork and branch**
- Fork the repository on GitHub.
- Create a branch from `main`: e.g. `git checkout -b fix/issue-123` or `feature/sub-improvements`.
2. **Make your changes**
- Follow the [Coding Conventions](#coding-conventions-and-style-guide).
- Run `gofmt` and ensure the project builds (see [Testing](#testing)).
- Keep commits focused and messages clear (e.g. "Fix link conversion for VMess", "Add tests for outJson").
3. **Push and open a PR**
- Push your branch and open a Pull Request against `main`.
- Use the PR description to explain:
- What problem or feature the PR addresses.
- What you changed and how to verify it.
- Reference any related issue (e.g. "Fixes #123").
4. **Review and CI**
- Maintainers will review your code. CI (e.g. build workflows) must pass.
- Address feedback by pushing new commits to the same branch.
5. **Merge**
- Once approved and CI is green, a maintainer will merge your PR. Thank you for contributing!
### PR Guidelines
- Prefer **small, reviewable PRs**. Split large features into logical steps.
- Avoid unrelated changes (e.g. formatting-only or refactors in a feature PR).
- Ensure your branch is up to date with `main` before submitting (rebase or merge as the project prefers).
---
## Adding This Guide in Your Repository
If you maintain a fork or your own repository and want the contribution guide to be visible and linked properly:
1. **Keep `CONTRIBUTING.md` in the repository root**
GitHub automatically discovers a file named `CONTRIBUTING.md` (or `CONTRIBUTING`) in the root. When someone opens a new issue or pull request, GitHub can show a link to it. The community profile also uses it for the “Contributing” section.
2. **Link from README**
Add a short line in your main `README.md` so new contributors see it when they land on the repo, for example:
```markdown
**Want to contribute?** See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding conventions, and the pull request process.
```
3. **Optional: GitHub “Contributing” link**
In the repository **Settings → General → Features**, ensure “Issues” (and optionally “Discussions”) are enabled. The link to `CONTRIBUTING.md` appears when users create a new issue or PR; no extra config is needed as long as the file is in the root.
4. **When forking**
If you fork S-UI, `CONTRIBUTING.md` is already in the repo. Update the clone URLs and repo names in this file if you want your fork’s contribution instructions to point to your own repository.
---
## Reporting Bugs and Requesting Features
- **Bugs**: Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md). Include version, OS, steps to reproduce, and expected vs actual behavior.
- **Features**: Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md). Describe the use case and, if possible, a proposed approach.
- **Questions**: Use the [question template](.github/ISSUE_TEMPLATE/question-template.md) or discussions if enabled.
---
Thank you for helping S-UI grow. Your contributions make it possible for more users to adopt S-UI in production and benefit from its multi-inbound-per-user design.
================================================
FILE: Dockerfile
================================================
FROM --platform=$BUILDPLATFORM node:alpine AS front-builder
WORKDIR /app
COPY frontend/ ./
RUN npm install && npm run build
FROM golang:1.25-alpine AS backend-builder
WORKDIR /app
ARG TARGETARCH
ARG TARGETVARIANT
ENV CGO_ENABLED=1
ENV CGO_CFLAGS="-D_LARGEFILE64_SOURCE"
ENV GOARCH=$TARGETARCH
RUN apk update && apk add --no-cache \
gcc \
musl-dev \
libc-dev \
make \
git \
wget \
unzip \
bash \
curl
ENV CC=gcc
RUN CRONET_ARCH="$TARGETARCH" && \
CRONET_URL="https://github.com/SagerNet/cronet-go/releases/latest/download/libcronet-linux-${CRONET_ARCH}.so"; \
echo "Downloading $CRONET_URL" && \
wget -q -O ./libcronet.so "$CRONET_URL" && \
chmod 755 ./libcronet.so
COPY . .
COPY --from=front-builder /app/dist/ /app/web/html/
RUN if [ "$TARGETARCH" = "arm" ]; then export GOARM=7; [ "$TARGETVARIANT" = "v6" ] && export GOARM=6; fi; \
go build -ldflags="-w -s" \
-tags "with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego" \
-o sui main.go
FROM alpine
LABEL org.opencontainers.image.authors="alireza7@gmail.com"
ENV TZ=Asia/Tehran
WORKDIR /app
RUN set -ex && apk add --no-cache --upgrade bash tzdata ca-certificates nftables
COPY --from=backend-builder /app/sui /app/libcronet.so /app/
COPY entrypoint.sh /app/
ENTRYPOINT [ "./entrypoint.sh" ]
================================================
FILE: Dockerfile.frontend-artifact
================================================
FROM golang:1.25-alpine AS backend-builder
WORKDIR /app
ARG TARGETARCH
ARG TARGETVARIANT
ENV CGO_ENABLED=1
ENV CGO_CFLAGS="-D_LARGEFILE64_SOURCE"
ENV GOARCH=$TARGETARCH
RUN apk update && apk add --no-cache \
gcc \
musl-dev \
libc-dev \
make \
git \
wget \
unzip \
bash \
curl
ENV CC=gcc
RUN CRONET_ARCH="$TARGETARCH" && \
CRONET_URL="https://github.com/SagerNet/cronet-go/releases/latest/download/libcronet-linux-${CRONET_ARCH}.so"; \
echo "Downloading $CRONET_URL" && \
wget -q -O ./libcronet.so "$CRONET_URL" && \
chmod 755 ./libcronet.so
COPY . .
COPY frontend_dist/ /app/web/html/
RUN if [ "$TARGETARCH" = "arm" ]; then export GOARM=7; [ "$TARGETVARIANT" = "v6" ] && export GOARM=6; fi; \
go build -ldflags="-w -s" \
-tags "with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego" \
-o sui main.go
FROM alpine
LABEL org.opencontainers.image.authors="alireza7@gmail.com"
ENV TZ=Asia/Tehran
WORKDIR /app
RUN set -ex && apk add --no-cache --upgrade bash tzdata ca-certificates nftables
COPY --from=backend-builder /app/sui /app/libcronet.so /app/
COPY entrypoint.sh /app/
ENTRYPOINT [ "./entrypoint.sh" ]
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# S-UI
**An Advanced Web Panel • Built on SagerNet/Sing-Box**


[](https://goreportcard.com/report/github.com/alireza0/s-ui)
[](https://img.shields.io/github/downloads/alireza0/s-ui/total.svg)
[](https://www.gnu.org/licenses/gpl-3.0.en.html)
> **Disclaimer:** This project is only for personal learning and communication, please do not use it for illegal purposes, please do not use it in a production environment
**If you think this project is helpful to you, you may wish to give a**:star2:
**Want to contribute?** See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding conventions, testing, and the pull request process.
[](https://www.buymeacoffee.com/alireza7)
<a href="https://nowpayments.io/donation/alireza7" target="_blank" rel="noreferrer noopener">
<img src="https://nowpayments.io/images/embeds/donation-button-white.svg" alt="Crypto donation button by NOWPayments">
</a>
## Quick Overview
| Features | Enable? |
| -------------------------------------- | :----------------: |
| Multi-Protocol | :heavy_check_mark: |
| Multi-Language | :heavy_check_mark: |
| Multi-Client/Inbound | :heavy_check_mark: |
| Advanced Traffic Routing Interface | :heavy_check_mark: |
| Client & Traffic & System Status | :heavy_check_mark: |
| Subscription Link (link/json/clash + info)| :heavy_check_mark: |
| Dark/Light Theme | :heavy_check_mark: |
| API Interface | :heavy_check_mark: |
## Supported Platforms
| Platform | Architecture | Status |
|----------|--------------|---------|
| Linux | amd64, arm64, armv7, armv6, armv5, 386, s390x | ✅ Supported |
| Windows | amd64, 386, arm64 | ✅ Supported |
| macOS | amd64, arm64 | 🚧 Experimental |
## Screenshots

[Other UI Screenshots](https://github.com/alireza0/s-ui-frontend/blob/main/screenshots.md)
## API Documentation
[API-Documentation Wiki](https://github.com/alireza0/s-ui/wiki/API-Documentation)
## Default Installation Information
- Panel Port: 2095
- Panel Path: /app/
- Subscription Port: 2096
- Subscription Path: /sub/
- User/Password: admin
## Install & Upgrade to Latest Version
### Linux/macOS
```sh
bash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/master/install.sh)
```
### Windows
1. Download the latest Windows release from [GitHub Releases](https://github.com/alireza0/s-ui/releases/latest)
2. Extract the ZIP file
3. Run `install-windows.bat` as Administrator
4. Follow the installation wizard
## Install legacy Version
**Step 1:** To install your desired legacy version, add the version to the end of the installation command. e.g., ver `1.0.0`:
```sh
VERSION=1.0.0 && bash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/$VERSION/install.sh) $VERSION
```
## Manual installation
### Linux/macOS
1. Get the latest version of S-UI based on your OS/Architecture from GitHub: [https://github.com/alireza0/s-ui/releases/latest](https://github.com/alireza0/s-ui/releases/latest)
2. **OPTIONAL** Get the latest version of `s-ui.sh` [https://raw.githubusercontent.com/alireza0/s-ui/master/s-ui.sh](https://raw.githubusercontent.com/alireza0/s-ui/master/s-ui.sh)
3. **OPTIONAL** Copy `s-ui.sh` to /usr/bin/ and run `chmod +x /usr/bin/s-ui`.
4. Extract s-ui tar.gz file to a directory of your choice and navigate to the directory where you extracted the tar.gz file.
5. Copy *.service files to /etc/systemd/system/ and run `systemctl daemon-reload`.
6. Enable autostart and start S-UI service using `systemctl enable s-ui --now`
7. Start sing-box service using `systemctl enable sing-box --now`
### Windows
1. Get the latest Windows version from GitHub: [https://github.com/alireza0/s-ui/releases/latest](https://github.com/alireza0/s-ui/releases/latest)
2. Download the appropriate Windows package (e.g., `s-ui-windows-amd64.zip`)
3. Extract the ZIP file to a directory of your choice
4. Run `install-windows.bat` as Administrator
5. Follow the installation wizard
6. Access the panel at http://localhost:2095/app
## Uninstall S-UI
```sh
sudo -i
systemctl disable s-ui --now
rm -f /etc/systemd/system/sing-box.service
systemctl daemon-reload
rm -fr /usr/local/s-ui
rm /usr/bin/s-ui
```
## Install using Docker
<details>
<summary>Click for details</summary>
### Usage
**Step 1:** Install Docker
```shell
curl -fsSL https://get.docker.com | sh
```
**Step 2:** Install S-UI
> Docker compose method
```shell
mkdir s-ui && cd s-ui
wget -q https://raw.githubusercontent.com/alireza0/s-ui/master/docker-compose.yml
docker compose up -d
```
> Use docker
```shell
mkdir s-ui && cd s-ui
docker run -itd \
-p 2095:2095 -p 2096:2096 -p 443:443 -p 80:80 \
-v $PWD/db/:/app/db/ \
-v $PWD/cert/:/root/cert/ \
--name s-ui --restart=unless-stopped \
alireza7/s-ui:latest
```
> Build your own image
```shell
git clone https://github.com/alireza0/s-ui
git submodule update --init --recursive
docker build -t s-ui .
```
</details>
## Manual run ( contribution )
<details>
<summary>Click for details</summary>
### Build and run whole project
```shell
./runSUI.sh
```
### Clone the repository
```shell
# clone repository
git clone https://github.com/alireza0/s-ui
# clone submodules
git submodule update --init --recursive
```
### - Frontend
Visit [s-ui-frontend](https://github.com/alireza0/s-ui-frontend) for frontend code
### - Backend
> Please build frontend once before!
To build backend:
```shell
# remove old frontend compiled files
rm -fr web/html/*
# apply new frontend compiled files
cp -R frontend/dist/ web/html/
# build
go build -o sui main.go
```
To run backend (from root folder of repository):
```shell
./sui
```
</details>
## Languages
- English
- Farsi
- Vietnamese
- Chinese (Simplified)
- Chinese (Traditional)
- Russian
## Features
- Supported protocols:
- General: Mixed, SOCKS, HTTP, HTTPS, Direct, Redirect, TProxy
- V2Ray based: VLESS, VMess, Trojan, Shadowsocks
- Other protocols: ShadowTLS, Hysteria, Hysteria2, Naive, TUIC
- Supports XTLS protocols
- An advanced interface for routing traffic, incorporating PROXY Protocol, External, and Transparent Proxy, SSL Certificate, and Port
- An advanced interface for inbound and outbound configuration
- Clients’ traffic cap and expiration date
- Displays online clients, inbounds and outbounds with traffic statistics, and system status monitoring
- Subscription service with ability to add external links and subscription
- HTTPS for secure access to the web panel and subscription service (self-provided domain + SSL certificate)
- Dark/Light theme
## Environment Variables
<details>
<summary>Click for details</summary>
### Usage
| Variable | Type | Default |
| -------------- | :--------------------------------------------: | :------------ |
| SUI_LOG_LEVEL | `"debug"` \| `"info"` \| `"warn"` \| `"error"` | `"info"` |
| SUI_DEBUG | `boolean` | `false` |
| SUI_BIN_FOLDER | `string` | `"bin"` |
| SUI_DB_FOLDER | `string` | `"db"` |
| SINGBOX_API | `string` | - |
</details>
## SSL Certificate
<details>
<summary>Click for details</summary>
### Certbot
```bash
snap install core; snap refresh core
snap install --classic certbot
ln -s /snap/bin/certbot /usr/bin/certbot
certbot certonly --standalone --register-unsafely-without-email --non-interactive --agree-tos -d <Your Domain Name>
```
</details>
## Stargazers over Time
[](https://starchart.cc/alireza0/s-ui)
================================================
FILE: api/apiHandler.go
================================================
package api
import (
"strings"
"github.com/alireza0/s-ui/util/common"
"github.com/gin-gonic/gin"
)
type APIHandler struct {
ApiService
apiv2 *APIv2Handler
}
func NewAPIHandler(g *gin.RouterGroup, a2 *APIv2Handler) {
a := &APIHandler{
apiv2: a2,
}
a.initRouter(g)
}
func (a *APIHandler) initRouter(g *gin.RouterGroup) {
g.Use(func(c *gin.Context) {
path := c.Request.URL.Path
if !strings.HasSuffix(path, "login") && !strings.HasSuffix(path, "logout") {
checkLogin(c)
}
})
g.POST("/:postAction", a.postHandler)
g.GET("/:getAction", a.getHandler)
}
func (a *APIHandler) postHandler(c *gin.Context) {
loginUser := GetLoginUser(c)
action := c.Param("postAction")
switch action {
case "login":
a.ApiService.Login(c)
case "changePass":
a.ApiService.ChangePass(c)
case "save":
a.ApiService.Save(c, loginUser)
case "restartApp":
a.ApiService.RestartApp(c)
case "restartSb":
a.ApiService.RestartSb(c)
case "linkConvert":
a.ApiService.LinkConvert(c)
case "subConvert":
a.ApiService.SubConvert(c)
case "importdb":
a.ApiService.ImportDb(c)
case "addToken":
a.ApiService.AddToken(c)
a.apiv2.ReloadTokens()
case "deleteToken":
a.ApiService.DeleteToken(c)
a.apiv2.ReloadTokens()
default:
jsonMsg(c, "failed", common.NewError("unknown action: ", action))
}
}
func (a *APIHandler) getHandler(c *gin.Context) {
action := c.Param("getAction")
switch action {
case "logout":
a.ApiService.Logout(c)
case "load":
a.ApiService.LoadData(c)
case "inbounds", "outbounds", "endpoints", "services", "tls", "clients", "config":
err := a.ApiService.LoadPartialData(c, []string{action})
if err != nil {
jsonMsg(c, action, err)
}
return
case "users":
a.ApiService.GetUsers(c)
case "settings":
a.ApiService.GetSettings(c)
case "stats":
a.ApiService.GetStats(c)
case "status":
a.ApiService.GetStatus(c)
case "onlines":
a.ApiService.GetOnlines(c)
case "logs":
a.ApiService.GetLogs(c)
case "changes":
a.ApiService.CheckChanges(c)
case "keypairs":
a.ApiService.GetKeypairs(c)
case "getdb":
a.ApiService.GetDb(c)
case "tokens":
a.ApiService.GetTokens(c)
case "singbox-config":
a.ApiService.GetSingboxConfig(c)
case "checkOutbound":
a.ApiService.GetCheckOutbound(c)
default:
jsonMsg(c, "failed", common.NewError("unknown action: ", action))
}
}
================================================
FILE: api/apiService.go
================================================
package api
import (
"encoding/json"
"strconv"
"time"
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/service"
"github.com/alireza0/s-ui/util"
"github.com/gin-gonic/gin"
)
type ApiService struct {
service.SettingService
service.UserService
service.ConfigService
service.ClientService
service.TlsService
service.InboundService
service.OutboundService
service.EndpointService
service.ServicesService
service.PanelService
service.StatsService
service.ServerService
}
func (a *ApiService) LoadData(c *gin.Context) {
data, err := a.getData(c)
if err != nil {
jsonMsg(c, "", err)
return
}
jsonObj(c, data, nil)
}
func (a *ApiService) getData(c *gin.Context) (interface{}, error) {
data := make(map[string]interface{}, 0)
lu := c.Query("lu")
isUpdated, err := a.ConfigService.CheckChanges(lu)
if err != nil {
return "", err
}
onlines, err := a.StatsService.GetOnlines()
sysInfo := a.ServerService.GetSingboxInfo()
if sysInfo["running"] == false {
logs := a.ServerService.GetLogs("1", "debug")
if len(logs) > 0 {
data["lastLog"] = logs[0]
}
}
if err != nil {
return "", err
}
if isUpdated {
config, err := a.SettingService.GetConfig()
if err != nil {
return "", err
}
clients, err := a.ClientService.GetAll()
if err != nil {
return "", err
}
tlsConfigs, err := a.TlsService.GetAll()
if err != nil {
return "", err
}
inbounds, err := a.InboundService.GetAll()
if err != nil {
return "", err
}
outbounds, err := a.OutboundService.GetAll()
if err != nil {
return "", err
}
endpoints, err := a.EndpointService.GetAll()
if err != nil {
return "", err
}
services, err := a.ServicesService.GetAll()
if err != nil {
return "", err
}
subURI, err := a.SettingService.GetFinalSubURI(getHostname(c))
if err != nil {
return "", err
}
trafficAge, err := a.SettingService.GetTrafficAge()
if err != nil {
return "", err
}
data["config"] = json.RawMessage(config)
data["clients"] = clients
data["tls"] = tlsConfigs
data["inbounds"] = inbounds
data["outbounds"] = outbounds
data["endpoints"] = endpoints
data["services"] = services
data["subURI"] = subURI
data["enableTraffic"] = trafficAge > 0
data["onlines"] = onlines
} else {
data["onlines"] = onlines
}
return data, nil
}
func (a *ApiService) LoadPartialData(c *gin.Context, objs []string) error {
data := make(map[string]interface{}, 0)
id := c.Query("id")
for _, obj := range objs {
switch obj {
case "inbounds":
inbounds, err := a.InboundService.Get(id)
if err != nil {
return err
}
data[obj] = inbounds
case "outbounds":
outbounds, err := a.OutboundService.GetAll()
if err != nil {
return err
}
data[obj] = outbounds
case "endpoints":
endpoints, err := a.EndpointService.GetAll()
if err != nil {
return err
}
data[obj] = endpoints
case "services":
services, err := a.ServicesService.GetAll()
if err != nil {
return err
}
data[obj] = services
case "tls":
tlsConfigs, err := a.TlsService.GetAll()
if err != nil {
return err
}
data[obj] = tlsConfigs
case "clients":
clients, err := a.ClientService.Get(id)
if err != nil {
return err
}
data[obj] = clients
case "config":
config, err := a.SettingService.GetConfig()
if err != nil {
return err
}
data[obj] = json.RawMessage(config)
case "settings":
settings, err := a.SettingService.GetAllSetting()
if err != nil {
return err
}
data[obj] = settings
}
}
jsonObj(c, data, nil)
return nil
}
func (a *ApiService) GetUsers(c *gin.Context) {
users, err := a.UserService.GetUsers()
if err != nil {
jsonMsg(c, "", err)
return
}
jsonObj(c, *users, nil)
}
func (a *ApiService) GetSettings(c *gin.Context) {
data, err := a.SettingService.GetAllSetting()
if err != nil {
jsonMsg(c, "", err)
return
}
jsonObj(c, data, err)
}
func (a *ApiService) GetStats(c *gin.Context) {
resource := c.Query("resource")
tag := c.Query("tag")
limit, err := strconv.Atoi(c.Query("limit"))
if err != nil {
limit = 100
}
data, err := a.StatsService.GetStats(resource, tag, limit)
if err != nil {
jsonMsg(c, "", err)
return
}
jsonObj(c, data, err)
}
func (a *ApiService) GetStatus(c *gin.Context) {
request := c.Query("r")
result := a.ServerService.GetStatus(request)
jsonObj(c, result, nil)
}
func (a *ApiService) GetOnlines(c *gin.Context) {
onlines, err := a.StatsService.GetOnlines()
jsonObj(c, onlines, err)
}
func (a *ApiService) GetLogs(c *gin.Context) {
count := c.Query("c")
level := c.Query("l")
logs := a.ServerService.GetLogs(count, level)
jsonObj(c, logs, nil)
}
func (a *ApiService) CheckChanges(c *gin.Context) {
actor := c.Query("a")
chngKey := c.Query("k")
count := c.Query("c")
changes := a.ConfigService.GetChanges(actor, chngKey, count)
jsonObj(c, changes, nil)
}
func (a *ApiService) GetKeypairs(c *gin.Context) {
kType := c.Query("k")
options := c.Query("o")
keypair := a.ServerService.GenKeypair(kType, options)
jsonObj(c, keypair, nil)
}
func (a *ApiService) GetDb(c *gin.Context) {
exclude := c.Query("exclude")
db, err := database.GetDb(exclude)
if err != nil {
jsonMsg(c, "", err)
return
}
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename=s-ui_"+time.Now().Format("20060102-150405")+".db")
c.Writer.Write(db)
}
func (a *ApiService) postActions(c *gin.Context) (string, json.RawMessage, error) {
var data map[string]json.RawMessage
err := c.ShouldBind(&data)
if err != nil {
return "", nil, err
}
return string(data["action"]), data["data"], nil
}
func (a *ApiService) Login(c *gin.Context) {
remoteIP := getRemoteIp(c)
loginUser, err := a.UserService.Login(c.Request.FormValue("user"), c.Request.FormValue("pass"), remoteIP)
if err != nil {
jsonMsg(c, "", err)
return
}
sessionMaxAge, err := a.SettingService.GetSessionMaxAge()
if err != nil {
logger.Infof("Unable to get session's max age from DB")
}
err = SetLoginUser(c, loginUser, sessionMaxAge)
if err == nil {
logger.Info("user ", loginUser, " login success")
} else {
logger.Warning("login failed: ", err)
}
jsonMsg(c, "", nil)
}
func (a *ApiService) ChangePass(c *gin.Context) {
id := c.Request.FormValue("id")
oldPass := c.Request.FormValue("oldPass")
newUsername := c.Request.FormValue("newUsername")
newPass := c.Request.FormValue("newPass")
err := a.UserService.ChangePass(id, oldPass, newUsername, newPass)
if err == nil {
logger.Info("change user credentials success")
jsonMsg(c, "save", nil)
} else {
logger.Warning("change user credentials failed:", err)
jsonMsg(c, "", err)
}
}
func (a *ApiService) Save(c *gin.Context, loginUser string) {
hostname := getHostname(c)
obj := c.Request.FormValue("object")
act := c.Request.FormValue("action")
data := c.Request.FormValue("data")
initUsers := c.Request.FormValue("initUsers")
objs, err := a.ConfigService.Save(obj, act, json.RawMessage(data), initUsers, loginUser, hostname)
if err != nil {
jsonMsg(c, "save", err)
return
}
err = a.LoadPartialData(c, objs)
if err != nil {
jsonMsg(c, obj, err)
}
}
func (a *ApiService) RestartApp(c *gin.Context) {
err := a.PanelService.RestartPanel(3)
jsonMsg(c, "restartApp", err)
}
func (a *ApiService) RestartSb(c *gin.Context) {
err := a.ConfigService.RestartCore()
jsonMsg(c, "restartSb", err)
}
func (a *ApiService) LinkConvert(c *gin.Context) {
link := c.Request.FormValue("link")
result, _, err := util.GetOutbound(link, 0)
jsonObj(c, result, err)
}
func (a *ApiService) SubConvert(c *gin.Context) {
link := c.Request.FormValue("link")
result, err := util.GetExternalSub(link)
jsonObj(c, result, err)
}
func (a *ApiService) ImportDb(c *gin.Context) {
file, _, err := c.Request.FormFile("db")
if err != nil {
jsonMsg(c, "", err)
return
}
defer file.Close()
err = database.ImportDB(file)
jsonMsg(c, "", err)
}
func (a *ApiService) Logout(c *gin.Context) {
loginUser := GetLoginUser(c)
if loginUser != "" {
logger.Infof("user %s logout", loginUser)
}
ClearSession(c)
jsonMsg(c, "", nil)
}
func (a *ApiService) LoadTokens() ([]byte, error) {
return a.UserService.LoadTokens()
}
func (a *ApiService) GetTokens(c *gin.Context) {
loginUser := GetLoginUser(c)
tokens, err := a.UserService.GetUserTokens(loginUser)
jsonObj(c, tokens, err)
}
func (a *ApiService) AddToken(c *gin.Context) {
loginUser := GetLoginUser(c)
expiry := c.Request.FormValue("expiry")
expiryInt, err := strconv.ParseInt(expiry, 10, 64)
if err != nil {
jsonMsg(c, "", err)
return
}
desc := c.Request.FormValue("desc")
token, err := a.UserService.AddToken(loginUser, expiryInt, desc)
jsonObj(c, token, err)
}
func (a *ApiService) DeleteToken(c *gin.Context) {
tokenId := c.Request.FormValue("id")
err := a.UserService.DeleteToken(tokenId)
jsonMsg(c, "", err)
}
func (a *ApiService) GetSingboxConfig(c *gin.Context) {
rawConfig, err := a.ConfigService.GetConfig("")
if err != nil {
c.Status(400)
c.Writer.WriteString(err.Error())
return
}
c.Header("Content-Type", "application/json")
c.Header("Content-Disposition", "attachment; filename=config_"+time.Now().Format("20060102-150405")+".json")
c.Writer.Write(*rawConfig)
}
func (a *ApiService) GetCheckOutbound(c *gin.Context) {
tag := c.Query("tag")
link := c.Query("link")
result := a.ConfigService.CheckOutbound(tag, link)
jsonObj(c, result, nil)
}
================================================
FILE: api/apiV2Handler.go
================================================
package api
import (
"encoding/json"
"time"
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/util/common"
"github.com/gin-gonic/gin"
)
type TokenInMemory struct {
Token string
Expiry int64
Username string
}
type APIv2Handler struct {
ApiService
tokens *[]TokenInMemory
}
func NewAPIv2Handler(g *gin.RouterGroup) *APIv2Handler {
a := &APIv2Handler{}
a.ReloadTokens()
a.initRouter(g)
return a
}
func (a *APIv2Handler) initRouter(g *gin.RouterGroup) {
g.Use(func(c *gin.Context) {
a.checkToken(c)
})
g.POST("/:postAction", a.postHandler)
g.GET("/:getAction", a.getHandler)
}
func (a *APIv2Handler) postHandler(c *gin.Context) {
username := a.findUsername(c)
action := c.Param("postAction")
switch action {
case "save":
a.ApiService.Save(c, username)
case "restartApp":
a.ApiService.RestartApp(c)
case "restartSb":
a.ApiService.RestartSb(c)
case "linkConvert":
a.ApiService.LinkConvert(c)
case "subConvert":
a.ApiService.SubConvert(c)
case "importdb":
a.ApiService.ImportDb(c)
default:
jsonMsg(c, "failed", common.NewError("unknown action: ", action))
}
}
func (a *APIv2Handler) getHandler(c *gin.Context) {
action := c.Param("getAction")
switch action {
case "load":
a.ApiService.LoadData(c)
case "inbounds", "outbounds", "endpoints", "services", "tls", "clients", "config":
err := a.ApiService.LoadPartialData(c, []string{action})
if err != nil {
jsonMsg(c, action, err)
}
return
case "users":
a.ApiService.GetUsers(c)
case "settings":
a.ApiService.GetSettings(c)
case "stats":
a.ApiService.GetStats(c)
case "status":
a.ApiService.GetStatus(c)
case "onlines":
a.ApiService.GetOnlines(c)
case "logs":
a.ApiService.GetLogs(c)
case "changes":
a.ApiService.CheckChanges(c)
case "keypairs":
a.ApiService.GetKeypairs(c)
case "getdb":
a.ApiService.GetDb(c)
case "checkOutbound":
a.ApiService.GetCheckOutbound(c)
default:
jsonMsg(c, "failed", common.NewError("unknown action: ", action))
}
}
func (a *APIv2Handler) findUsername(c *gin.Context) string {
token := c.Request.Header.Get("Token")
for index, t := range *a.tokens {
if t.Expiry > 0 && t.Expiry < time.Now().Unix() {
(*a.tokens) = append((*a.tokens)[:index], (*a.tokens)[index+1:]...)
continue
}
if t.Token == token {
return t.Username
}
}
return ""
}
func (a *APIv2Handler) checkToken(c *gin.Context) {
username := a.findUsername(c)
if username != "" {
c.Next()
return
}
jsonMsg(c, "", common.NewError("invalid token"))
c.Abort()
}
func (a *APIv2Handler) ReloadTokens() {
tokens, err := a.ApiService.LoadTokens()
if err == nil {
var newTokens []TokenInMemory
err = json.Unmarshal(tokens, &newTokens)
if err != nil {
logger.Error("unable to load tokens: ", err)
}
a.tokens = &newTokens
} else {
logger.Error("unable to load tokens: ", err)
}
}
================================================
FILE: api/session.go
================================================
package api
import (
"encoding/gob"
"github.com/alireza0/s-ui/database/model"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
const (
loginUser = "LOGIN_USER"
)
func init() {
gob.Register(model.User{})
}
func SetLoginUser(c *gin.Context, userName string, maxAge int) error {
options := sessions.Options{
Path: "/",
Secure: false,
}
if maxAge > 0 {
options.MaxAge = maxAge * 60
}
s := sessions.Default(c)
s.Set(loginUser, userName)
s.Options(options)
return s.Save()
}
func SetMaxAge(c *gin.Context) error {
s := sessions.Default(c)
s.Options(sessions.Options{
Path: "/",
})
return s.Save()
}
func GetLoginUser(c *gin.Context) string {
s := sessions.Default(c)
obj := s.Get(loginUser)
if obj == nil {
return ""
}
objStr, ok := obj.(string)
if !ok {
return ""
}
return objStr
}
func IsLogin(c *gin.Context) bool {
return GetLoginUser(c) != ""
}
func ClearSession(c *gin.Context) {
s := sessions.Default(c)
s.Clear()
s.Options(sessions.Options{
Path: "/",
MaxAge: -1,
})
s.Save()
}
================================================
FILE: api/utils.go
================================================
package api
import (
"net"
"net/http"
"strings"
"github.com/alireza0/s-ui/logger"
"github.com/gin-gonic/gin"
)
type Msg struct {
Success bool `json:"success"`
Msg string `json:"msg"`
Obj interface{} `json:"obj"`
}
func getRemoteIp(c *gin.Context) string {
value := c.GetHeader("X-Forwarded-For")
if value != "" {
ips := strings.Split(value, ",")
return ips[0]
} else {
addr := c.Request.RemoteAddr
ip, _, _ := net.SplitHostPort(addr)
return ip
}
}
func getHostname(c *gin.Context) string {
host := c.Request.Host
if strings.Contains(host, ":") {
host, _, _ = net.SplitHostPort(c.Request.Host)
if strings.Contains(host, ":") {
host = "[" + host + "]"
}
}
return host
}
func jsonMsg(c *gin.Context, msg string, err error) {
jsonMsgObj(c, msg, nil, err)
}
func jsonObj(c *gin.Context, obj interface{}, err error) {
jsonMsgObj(c, "", obj, err)
}
func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
m := Msg{
Obj: obj,
}
if err == nil {
m.Success = true
if msg != "" {
m.Msg = msg
}
} else {
m.Success = false
m.Msg = msg + ": " + err.Error()
logger.Warning("failed :", err)
}
c.JSON(http.StatusOK, m)
}
func pureJsonMsg(c *gin.Context, success bool, msg string) {
if success {
c.JSON(http.StatusOK, Msg{
Success: true,
Msg: msg,
})
} else {
c.JSON(http.StatusOK, Msg{
Success: false,
Msg: msg,
})
}
}
func checkLogin(c *gin.Context) {
if !IsLogin(c) {
if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
pureJsonMsg(c, false, "Invalid login")
} else {
c.Redirect(http.StatusTemporaryRedirect, "/login")
}
c.Abort()
} else {
c.Next()
}
}
================================================
FILE: app/app.go
================================================
package app
import (
"log"
"github.com/alireza0/s-ui/config"
"github.com/alireza0/s-ui/core"
"github.com/alireza0/s-ui/cronjob"
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/service"
"github.com/alireza0/s-ui/sub"
"github.com/alireza0/s-ui/web"
"github.com/op/go-logging"
)
type APP struct {
service.SettingService
configService *service.ConfigService
webServer *web.Server
subServer *sub.Server
cronJob *cronjob.CronJob
logger *logging.Logger
core *core.Core
}
func NewApp() *APP {
return &APP{}
}
func (a *APP) Init() error {
log.Printf("%v %v", config.GetName(), config.GetVersion())
a.initLog()
err := database.InitDB(config.GetDBPath())
if err != nil {
return err
}
// Init Setting
a.SettingService.GetAllSetting()
a.core = core.NewCore()
a.cronJob = cronjob.NewCronJob()
a.webServer = web.NewServer()
a.subServer = sub.NewServer()
a.configService = service.NewConfigService(a.core)
return nil
}
func (a *APP) Start() error {
loc, err := a.SettingService.GetTimeLocation()
if err != nil {
return err
}
trafficAge, err := a.SettingService.GetTrafficAge()
if err != nil {
return err
}
err = a.cronJob.Start(loc, trafficAge)
if err != nil {
return err
}
err = a.webServer.Start()
if err != nil {
return err
}
err = a.subServer.Start()
if err != nil {
return err
}
err = a.configService.StartCore()
if err != nil {
logger.Error(err)
}
return nil
}
func (a *APP) Stop() {
a.cronJob.Stop()
err := a.subServer.Stop()
if err != nil {
logger.Warning("stop Sub Server err:", err)
}
err = a.webServer.Stop()
if err != nil {
logger.Warning("stop Web Server err:", err)
}
err = a.configService.StopCore()
if err != nil {
logger.Warning("stop Core err:", err)
}
}
func (a *APP) initLog() {
switch config.GetLogLevel() {
case config.Debug:
logger.InitLogger(logging.DEBUG)
case config.Info:
logger.InitLogger(logging.INFO)
case config.Warn:
logger.InitLogger(logging.WARNING)
case config.Error:
logger.InitLogger(logging.ERROR)
default:
log.Fatal("unknown log level:", config.GetLogLevel())
}
}
func (a *APP) RestartApp() {
a.Stop()
a.Start()
}
func (a *APP) GetCore() *core.Core {
return a.core
}
================================================
FILE: build.sh
================================================
#!/bin/sh
cd frontend
npm i
npm run build
cd ..
echo "Backend"
mkdir -p web/html
rm -fr web/html/*
cp -R frontend/dist/* web/html/
BUILD_TAGS="with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_musl,badlinkname,tfogo_checklinkname0"
go build -ldflags '-w -s -checklinkname=0 -extldflags "-Wl,-no_warn_duplicate_libraries"' -tags "$BUILD_TAGS" -o sui main.go
================================================
FILE: cmd/admin.go
================================================
package cmd
import (
"fmt"
"github.com/alireza0/s-ui/config"
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/service"
)
func resetAdmin() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
userService := service.UserService{}
err = userService.UpdateFirstUser("admin", "admin")
if err != nil {
fmt.Println("reset admin credentials failed:", err)
} else {
fmt.Println("reset admin credentials success")
}
}
func updateAdmin(username string, password string) {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
if username != "" || password != "" {
userService := service.UserService{}
err := userService.UpdateFirstUser(username, password)
if err != nil {
fmt.Println("reset admin credentials failed:", err)
} else {
fmt.Println("reset admin credentials success")
}
}
}
func showAdmin() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
userService := service.UserService{}
userModel, err := userService.GetFirstUser()
if err != nil {
fmt.Println("get current user info failed,error info:", err)
}
username := userModel.Username
userpasswd := userModel.Password
if (username == "") || (userpasswd == "") {
fmt.Println("current username or password is empty")
}
fmt.Println("First admin credentials:")
fmt.Println("\tUsername:\t", username)
fmt.Println("\tPassword:\t", userpasswd)
}
================================================
FILE: cmd/cmd.go
================================================
package cmd
import (
"flag"
"fmt"
"os"
"runtime/debug"
"github.com/alireza0/s-ui/cmd/migration"
"github.com/alireza0/s-ui/config"
)
func ParseCmd() {
var showVersion bool
flag.BoolVar(&showVersion, "v", false, "show version")
adminCmd := flag.NewFlagSet("admin", flag.ExitOnError)
settingCmd := flag.NewFlagSet("setting", flag.ExitOnError)
var username string
var password string
var port int
var path string
var subPort int
var subPath string
var reset bool
var show bool
settingCmd.BoolVar(&reset, "reset", false, "reset all settings")
settingCmd.BoolVar(&show, "show", false, "show current settings")
settingCmd.IntVar(&port, "port", 0, "set panel port")
settingCmd.StringVar(&path, "path", "", "set panel path")
settingCmd.IntVar(&subPort, "subPort", 0, "set sub port")
settingCmd.StringVar(&subPath, "subPath", "", "set sub path")
adminCmd.BoolVar(&show, "show", false, "show first admin credentials")
adminCmd.BoolVar(&reset, "reset", false, "reset first admin credentials")
adminCmd.StringVar(&username, "username", "", "set login username")
adminCmd.StringVar(&password, "password", "", "set login password")
oldUsage := flag.Usage
flag.Usage = func() {
oldUsage()
fmt.Println()
fmt.Println("Commands:")
fmt.Println(" admin set/reset/show first admin credentials")
fmt.Println(" uri Show panel URI")
fmt.Println(" migrate migrate form older version")
fmt.Println(" setting set/reset/show settings")
fmt.Println()
adminCmd.Usage()
fmt.Println()
settingCmd.Usage()
}
flag.Parse()
if showVersion {
fmt.Println("S-UI Panel\t", config.GetVersion())
info, ok := debug.ReadBuildInfo()
if ok {
for _, dep := range info.Deps {
if dep.Path == "github.com/sagernet/sing-box" {
fmt.Println("Sing-Box\t", dep.Version)
break
}
}
}
return
}
switch os.Args[1] {
case "admin":
err := adminCmd.Parse(os.Args[2:])
if err != nil {
fmt.Println(err)
return
}
switch {
case show:
showAdmin()
case reset:
resetAdmin()
default:
updateAdmin(username, password)
showAdmin()
}
case "uri":
getPanelURI()
case "migrate":
migration.MigrateDb()
case "setting":
err := settingCmd.Parse(os.Args[2:])
if err != nil {
fmt.Println(err)
return
}
switch {
case show:
showSetting()
case reset:
resetSetting()
default:
updateSetting(port, path, subPort, subPath)
showSetting()
}
default:
fmt.Println("Invalid subcommands")
flag.Usage()
}
}
================================================
FILE: cmd/migration/1_1.go
================================================
package migration
import (
"encoding/json"
"fmt"
"strings"
"github.com/alireza0/s-ui/database/model"
"gorm.io/gorm"
)
func migrateClientSchema(db *gorm.DB) error {
rows, err := db.Raw("PRAGMA table_info(clients)").Rows()
if err != nil {
fmt.Println(err)
return err
}
defer rows.Close()
for rows.Next() {
var (
cid int
cname string
ctype string
notnull int
dfltValue interface{}
pk int
)
rows.Scan(&cid, &cname, &ctype, ¬null, &dfltValue, &pk)
if cname == "config" || cname == "inbounds" || cname == "links" {
if ctype == "text" {
fmt.Printf("Column %s has type TEXT\n", cname)
oldData := make([]struct {
Id uint
Data string
}, 0)
db.Model(model.Client{}).Select("id", cname+" as data").Scan(&oldData)
for _, data := range oldData {
var newData []byte
switch cname {
case "inbounds":
inbounds := strings.Split(data.Data, ",")
newData, _ = json.MarshalIndent(inbounds, "", " ")
case "config":
jsonData := map[string]interface{}{}
json.Unmarshal([]byte(data.Data), &jsonData)
newData, _ = json.MarshalIndent(jsonData, "", " ")
case "links":
jsonData := make([]interface{}, 0)
json.Unmarshal([]byte(data.Data), &jsonData)
newData, _ = json.MarshalIndent(jsonData, "", " ")
}
err = db.Model(model.Client{}).Where("id = ?", data.Id).UpdateColumn(cname, newData).Error
if err != nil {
return err
}
}
}
}
}
return nil
}
func deleteOldWebSecret(db *gorm.DB) error {
return db.Exec("DELETE FROM settings WHERE key = ?", "webSecret").Error
}
func changesObj(db *gorm.DB) error {
return db.Exec("UPDATE changes SET obj = CAST('\"' || CAST(obj AS TEXT) || '\"' AS BLOB) WHERE actor = ? and obj not like ?", "DepleteJob", "\"%\"").Error
}
func to1_1(db *gorm.DB) error {
err := migrateClientSchema(db)
if err != nil {
return err
}
err = deleteOldWebSecret(db)
if err != nil {
return err
}
err = changesObj(db)
if err != nil {
return err
}
return nil
}
================================================
FILE: cmd/migration/1_2.go
================================================
package migration
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"github.com/alireza0/s-ui/database/model"
"gorm.io/gorm"
)
type InboundData struct {
Id uint
Tag string
Addrs json.RawMessage
OutJson json.RawMessage
}
func moveJsonToDb(db *gorm.DB) error {
binFolderPath := os.Getenv("SUI_BIN_FOLDER")
if binFolderPath == "" {
binFolderPath = "bin"
}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
configPath := dir + "/" + binFolderPath + "/config.json"
if _, err := os.Stat(configPath); errors.Is(err, os.ErrNotExist) {
return nil
}
data, err := os.ReadFile(configPath)
if err != nil {
return err
}
var oldConfig map[string]interface{}
err = json.Unmarshal(data, &oldConfig)
if err != nil {
return err
}
oldInbounds := oldConfig["inbounds"].([]interface{})
db.Migrator().DropTable(&model.Inbound{})
db.AutoMigrate(&model.Inbound{})
for _, inbound := range oldInbounds {
inbObj, _ := inbound.(map[string]interface{})
tag, _ := inbObj["tag"].(string)
if tlsObj, ok := inbObj["tls"]; ok {
var tls_id uint
err = db.Raw("SELECT id FROM tls WHERE inbounds like ?", `%"`+tag+`"%`).Find(&tls_id).Error
if err != nil {
return err
}
// Bind or Create tls_id
if tls_id > 0 {
inbObj["tls_id"] = tls_id
} else {
tls_server, _ := json.MarshalIndent(tlsObj, "", " ")
if len(tls_server) > 5 {
newTls := &model.Tls{
Name: tag,
Server: tls_server,
Client: json.RawMessage("{}"),
}
err = db.Create(newTls).Error
if err != nil {
return err
}
inbObj["tls_id"] = newTls.Id
}
}
}
var inbData InboundData
db.Raw("select id,addrs,out_json from inbound_data where tag = ?", tag).Find(&inbData)
if inbData.Id > 0 {
inbObj["out_json"] = inbData.OutJson
var addrs []map[string]interface{}
json.Unmarshal(inbData.Addrs, &addrs)
for index, addr := range addrs {
if tlsEnable, ok := addr["tls"].(bool); ok {
newTls := map[string]interface{}{
"enabled": tlsEnable,
}
if insecure, ok := addr["insecure"].(bool); ok {
newTls["insecure"] = insecure
delete(addrs[index], "insecure")
}
if sni, ok := addr["server_name"].(string); ok {
newTls["server_name"] = sni
delete(addrs[index], "server_name")
}
addrs[index]["tls"] = newTls
}
}
inbObj["addrs"] = addrs
} else {
inbObj["out_json"] = json.RawMessage("{}")
inbObj["addrs"] = json.RawMessage("[]")
}
// Delete deprecated fields
delete(inbObj, "sniff")
delete(inbObj, "sniff_override_destination")
delete(inbObj, "sniff_timeout")
delete(inbObj, "domain_strategy")
inbJson, _ := json.Marshal(inbObj)
var newInbound model.Inbound
err = newInbound.UnmarshalJSON(inbJson)
if err != nil {
return err
}
err = db.Create(&newInbound).Error
if err != nil {
return err
}
}
delete(oldConfig, "inbounds")
blockOutboundTags := []string{}
dnsOutboundTags := []string{}
oldOutbounds := oldConfig["outbounds"].([]interface{})
db.Migrator().DropTable(&model.Outbound{}, &model.Endpoint{})
db.AutoMigrate(&model.Outbound{}, &model.Endpoint{})
for _, outbound := range oldOutbounds {
outType, _ := outbound.(map[string]interface{})["type"].(string)
outboundRaw, _ := json.MarshalIndent(outbound, "", " ")
if outType == "wireguard" { // Check if it is Entrypoint
var newEntrypoint model.Endpoint
err = newEntrypoint.UnmarshalJSON(outboundRaw)
if err != nil {
return err
}
err = db.Create(&newEntrypoint).Error
if err != nil {
return err
}
} else { // It is Outbound
var newOutbound model.Outbound
err = newOutbound.UnmarshalJSON(outboundRaw)
if err != nil {
return err
}
// Delete deprecated fields
if newOutbound.Type == "direct" {
var options map[string]interface{}
json.Unmarshal(newOutbound.Options, &options)
delete(options, "override_address")
delete(options, "override_port")
newOutbound.Options, _ = json.Marshal(options)
}
switch newOutbound.Type {
case "dns":
dnsOutboundTags = append(dnsOutboundTags, newOutbound.Tag)
case "block":
blockOutboundTags = append(blockOutboundTags, newOutbound.Tag)
default:
err = db.Create(&newOutbound).Error
if err != nil {
return err
}
}
}
}
delete(oldConfig, "outbounds")
// Check routing rules
if routingRules, ok := oldConfig["route"].(map[string]interface{}); ok {
if rules, hasRules := routingRules["rules"].([]interface{}); hasRules {
hasDns := false
for index, rule := range rules {
ruleObj, _ := rule.(map[string]interface{})
isBlock := false
isDns := false
outboundTag, _ := ruleObj["outbound"].(string)
for _, tag := range blockOutboundTags {
if tag == outboundTag {
isBlock = true
delete(ruleObj, "outbound")
ruleObj["action"] = "reject"
break
}
}
for _, tag := range dnsOutboundTags {
if tag == outboundTag {
isDns = true
hasDns = true
delete(ruleObj, "outbound")
ruleObj["action"] = "hijack-dns"
break
}
}
if !isBlock && !isDns {
ruleObj["action"] = "route"
}
rules[index] = ruleObj
}
if hasDns {
rules = append(rules, map[string]interface{}{"action": "sniff"})
}
routingRules["rules"] = rules
}
oldConfig["route"] = routingRules
}
// Remove v2rayapi and clashapi from experimental config
experimental := oldConfig["experimental"].(map[string]interface{})
delete(experimental, "v2ray_api")
delete(experimental, "clash_api")
oldConfig["experimental"] = experimental
// Save the other configs
var otherConfigs json.RawMessage
otherConfigs, err = json.MarshalIndent(oldConfig, "", " ")
if err != nil {
return err
}
return db.Save(&model.Setting{
Key: "config",
Value: string(otherConfigs),
}).Error
}
func migrateTls(db *gorm.DB) error {
if !db.Migrator().HasColumn(&model.Tls{}, "inbounds") {
return nil
}
err := db.Migrator().DropColumn(&model.Tls{}, "inbounds")
if err != nil {
return err
}
var tlsConfig []model.Tls
err = db.Model(model.Tls{}).Scan(&tlsConfig).Error
if err != nil {
return err
}
for index, tls := range tlsConfig {
var tlsClient map[string]interface{}
err = json.Unmarshal(tls.Client, &tlsClient)
if err != nil {
continue
}
for key := range tlsClient {
switch key {
case "insecure", "disable_sni", "utls", "ech", "reality":
continue
default:
delete(tlsClient, key)
}
}
tlsConfig[index].Client, _ = json.MarshalIndent(tlsClient, "", " ")
}
return db.Save(&tlsConfig).Error
}
func dropInboundData(db *gorm.DB) error {
if !db.Migrator().HasTable(&InboundData{}) {
return nil
}
return db.Migrator().DropTable(&InboundData{})
}
func migrateClients(db *gorm.DB) error {
var oldClients []model.Client
err := db.Model(model.Client{}).Scan(&oldClients).Error
if err != nil {
return err
}
for index, oldClient := range oldClients {
var old_inbounds []string
err = json.Unmarshal(oldClient.Inbounds, &old_inbounds)
if err != nil {
return err
}
var inbound_ids []uint
err = db.Raw("SELECT id FROM inbounds WHERE tag in ?", old_inbounds).Find(&inbound_ids).Error
if err != nil {
return err
}
oldClients[index].Inbounds, _ = json.Marshal(inbound_ids)
}
return db.Save(oldClients).Error
}
func migrateChanges(db *gorm.DB) error {
return db.Migrator().DropColumn(&model.Changes{}, "index")
}
func to1_2(db *gorm.DB) error {
err := moveJsonToDb(db)
if err != nil {
return err
}
err = migrateTls(db)
if err != nil {
return err
}
err = dropInboundData(db)
if err != nil {
return err
}
err = migrateClients(db)
if err != nil {
return err
}
return migrateChanges(db)
}
================================================
FILE: cmd/migration/1_3.go
================================================
package migration
import (
"encoding/json"
"net/url"
"strconv"
"strings"
"github.com/alireza0/s-ui/database/model"
"gorm.io/gorm"
)
func migrate_dns(db *gorm.DB) error {
var configStr string
err := db.Model(model.Setting{}).Select("value").Where("key = ?", "config").First(&configStr).Error
if err != nil {
return err
}
if configStr == "" {
return nil
}
var config map[string]interface{}
err = json.Unmarshal([]byte(configStr), &config)
if err != nil {
return err
}
if dnsConfig, ok := config["dns"].(map[string]interface{}); ok {
if dnsServers, ok := dnsConfig["servers"].([]interface{}); ok {
for index, dnsServer := range dnsServers {
if dnsServer, ok := dnsServer.(map[string]interface{}); ok {
if addr, ok := dnsServer["address"].(string); ok && addr != "" {
switch addr {
case "local":
delete(dnsServer, "address")
dnsServer["type"] = "local"
case "fakeip":
delete(dnsServer, "address")
dnsServer["type"] = "fakeip"
default:
addrParsed, err := url.Parse(addr)
if err != nil {
continue
}
switch addrParsed.Scheme {
case "":
dnsServer["type"] = "udp"
dnsServer["server"] = addr
case "udp", "tcp", "tls", "quic", "https", "h3":
dnsServer["type"] = addrParsed.Scheme
dnsServer["server"] = addrParsed.Host
case "dhcp":
dnsServer["type"] = addrParsed.Scheme
if addrParsed.Host != "auto" && addrParsed.Host != "" {
dnsServer["interface"] = addrParsed.Host
}
case "rcode":
dnsServer["type"] = "predefined"
dnsServer["responses"] = []map[string]string{
{
"rcode": strings.ToUpper(addrParsed.Host),
},
}
}
delete(dnsServer, "address")
if addrParsed.Port() != "" {
port, err := strconv.Atoi(addrParsed.Port())
if err == nil {
dnsServer["server_port"] = port
}
}
if address_resolver, ok := dnsServer["address_resolver"].(string); ok && address_resolver != "" {
delete(dnsServer, "address_resolver")
dnsServer["domain_resolver"] = address_resolver
}
delete(dnsServer, "strategy")
}
dnsServers[index] = dnsServer
}
}
}
dnsConfig["servers"] = dnsServers
}
config["dns"] = dnsConfig
} else {
return nil
}
// save changes
configs, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return db.Model(model.Setting{}).Where("key = ?", "config").Update("value", string(configs)).Error
}
func remove_outbound_strategy(db *gorm.DB) error {
var outbounds []model.Outbound
err := db.Find(&outbounds).Where("json_extract(options, '$.domain_strategy') IS NOT NULL").Error
if err != nil {
return err
}
for _, outbound := range outbounds {
var restFields map[string]json.RawMessage
if err := json.Unmarshal(outbound.Options, &restFields); err != nil {
return err
}
delete(restFields, "domain_strategy")
outbound.Options, _ = json.MarshalIndent(restFields, "", " ")
db.Save(&outbound)
}
return nil
}
func anytls_user_config(db *gorm.DB) error {
var clients []model.Client
err := db.Model(model.Client{}).Find(&clients).Error
if err != nil {
return err
}
for index, client := range clients {
var configs map[string]json.RawMessage
if err := json.Unmarshal(client.Config, &configs); err != nil {
return err
}
if configs["anytls"] != nil {
continue
}
configs["anytls"] = configs["trojan"]
configJson, err := json.MarshalIndent(configs, "", " ")
if err != nil {
return err
}
clients[index].Config = configJson
db.Save(&clients[index])
}
return nil
}
func to1_3(db *gorm.DB) error {
err := anytls_user_config(db)
if err != nil {
return err
}
err = migrate_dns(db)
if err != nil {
return err
}
err = remove_outbound_strategy(db)
if err != nil {
return err
}
return nil
}
================================================
FILE: cmd/migration/main.go
================================================
package migration
import (
"fmt"
"log"
"os"
"github.com/alireza0/s-ui/config"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func MigrateDb() {
// void running on first install
path := config.GetDBPath()
_, err := os.Stat(path)
if err != nil {
println("Database not found")
return
}
db, err := gorm.Open(sqlite.Open(path))
if err != nil {
log.Fatal(err)
return
}
tx := db.Begin()
defer func() {
if err == nil {
tx.Commit()
} else {
tx.Rollback()
}
}()
currentVersion := config.GetVersion()
dbVersion := ""
tx.Raw("SELECT value FROM settings WHERE key = ?", "version").Find(&dbVersion)
fmt.Println("Current version:", currentVersion, "\nDatabase version:", dbVersion)
if currentVersion == dbVersion {
fmt.Println("Database is up to date, no need to migrate")
return
}
fmt.Println("Start migrating database...")
// Before 1.2
if dbVersion == "" {
err = to1_1(tx)
if err != nil {
log.Fatal("Migration to 1.1 failed: ", err)
return
}
err = to1_2(tx)
if err != nil {
log.Fatal("Migration to 1.2 failed: ", err)
return
}
dbVersion = "1.2"
}
// Before 1.3
if dbVersion[0:3] == "1.2" {
err = to1_3(tx)
if err != nil {
log.Fatal("Migration to 1.3 failed: ", err)
return
}
}
// Set version
err = tx.Exec("UPDATE settings SET value = ? WHERE key = ?", currentVersion, "version").Error
if err != nil {
log.Fatal("Update version failed: ", err)
return
}
fmt.Println("Migration done!")
}
================================================
FILE: cmd/setting.go
================================================
package cmd
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/alireza0/s-ui/config"
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/service"
"github.com/shirou/gopsutil/v4/net"
)
func resetSetting() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
settingService := service.SettingService{}
err = settingService.ResetSettings()
if err != nil {
fmt.Println("reset setting failed:", err)
} else {
fmt.Println("reset setting success")
}
}
func updateSetting(port int, path string, subPort int, subPath string) {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
settingService := service.SettingService{}
if port > 0 {
err := settingService.SetPort(port)
if err != nil {
fmt.Println("set port failed:", err)
} else {
fmt.Println("set port success")
}
}
if path != "" {
err := settingService.SetWebPath(path)
if err != nil {
fmt.Println("set path failed:", err)
} else {
fmt.Println("set path success")
}
}
if subPort > 0 {
err := settingService.SetSubPort(subPort)
if err != nil {
fmt.Println("set sub port failed:", err)
} else {
fmt.Println("set sub port success")
}
}
if subPath != "" {
err := settingService.SetSubPath(subPath)
if err != nil {
fmt.Println("set sub path failed:", err)
} else {
fmt.Println("set sub path success")
}
}
}
func showSetting() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
settingService := service.SettingService{}
allSetting, err := settingService.GetAllSetting()
if err != nil {
fmt.Println("get current port failed,error info:", err)
}
fmt.Println("Current panel settings:")
fmt.Println("\tPanel port:\t", (*allSetting)["webPort"])
fmt.Println("\tPanel path:\t", (*allSetting)["webPath"])
if (*allSetting)["webListen"] != "" {
fmt.Println("\tPanel IP:\t", (*allSetting)["webListen"])
}
if (*allSetting)["webDomain"] != "" {
fmt.Println("\tPanel Domain:\t", (*allSetting)["webDomain"])
}
if (*allSetting)["webURI"] != "" {
fmt.Println("\tPanel URI:\t", (*allSetting)["webURI"])
}
fmt.Println()
fmt.Println("Current subscription settings:")
fmt.Println("\tSub port:\t", (*allSetting)["subPort"])
fmt.Println("\tSub path:\t", (*allSetting)["subPath"])
if (*allSetting)["subListen"] != "" {
fmt.Println("\tSub IP:\t", (*allSetting)["subListen"])
}
if (*allSetting)["subDomain"] != "" {
fmt.Println("\tSub Domain:\t", (*allSetting)["subDomain"])
}
if (*allSetting)["subURI"] != "" {
fmt.Println("\tSub URI:\t", (*allSetting)["subURI"])
}
}
func getPublicIP() string {
apis := []string{
"https://api64.ipify.org",
"https://ip.sb",
"https://icanhazip.com",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
}
type result struct {
ip string
err error
}
ch := make(chan result, len(apis))
var wg sync.WaitGroup
client := &http.Client{Timeout: 3 * time.Second}
for _, api := range apis {
wg.Add(1)
go func(url string) {
defer wg.Done()
resp, err := client.Get(url)
if err != nil {
ch <- result{"", err}
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
ch <- result{"", err}
return
}
ch <- result{string(body), nil}
}(api)
}
go func() {
wg.Wait()
close(ch)
}()
for res := range ch {
if res.err == nil && res.ip != "" {
return strings.TrimSpace(res.ip)
}
}
return ""
}
func getPanelURI() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
return
}
settingService := service.SettingService{}
Port, _ := settingService.GetPort()
BasePath, _ := settingService.GetWebPath()
Listen, _ := settingService.GetListen()
Domain, _ := settingService.GetWebDomain()
KeyFile, _ := settingService.GetKeyFile()
CertFile, _ := settingService.GetCertFile()
TLS := false
if KeyFile != "" && CertFile != "" {
TLS = true
}
Proto := ""
if TLS {
Proto = "https://"
} else {
Proto = "http://"
}
PortText := fmt.Sprintf(":%d", Port)
if (Port == 443 && TLS) || (Port == 80 && !TLS) {
PortText = ""
}
if len(Domain) > 0 {
fmt.Println(Proto + Domain + PortText + BasePath)
return
}
if len(Listen) > 0 {
fmt.Println(Proto + Listen + PortText + BasePath)
return
}
fmt.Println("Local address:")
netInterfaces, _ := net.Interfaces()
for i := 0; i < len(netInterfaces); i++ {
if len(netInterfaces[i].Flags) > 2 && netInterfaces[i].Flags[0] == "up" && netInterfaces[i].Flags[1] != "loopback" {
addrs := netInterfaces[i].Addrs
for _, address := range addrs {
IP := strings.Split(address.Addr, "/")[0]
if strings.Contains(address.Addr, ".") {
fmt.Println(Proto + IP + PortText + BasePath)
} else if address.Addr[0:6] != "fe80::" {
fmt.Println(Proto + "[" + IP + "]" + PortText + BasePath)
}
}
}
}
pubIP := getPublicIP()
if pubIP != "" {
fmt.Printf("\nGlobal address:\n%s%s%s\n", Proto, pubIP, PortText+BasePath)
}
}
================================================
FILE: config/config.go
================================================
package config
import (
_ "embed"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
//go:embed version
var version string
//go:embed name
var name string
type LogLevel string
const (
Debug LogLevel = "debug"
Info LogLevel = "info"
Warn LogLevel = "warn"
Error LogLevel = "error"
)
func GetVersion() string {
return strings.TrimSpace(version)
}
func GetName() string {
return strings.TrimSpace(name)
}
func GetLogLevel() LogLevel {
if IsDebug() {
return Debug
}
logLevel := os.Getenv("SUI_LOG_LEVEL")
if logLevel == "" {
return Info
}
return LogLevel(logLevel)
}
func IsDebug() bool {
return os.Getenv("SUI_DEBUG") == "true"
}
func GetDBFolderPath() string {
dbFolderPath := os.Getenv("SUI_DB_FOLDER")
if dbFolderPath == "" {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
// Cross-platform fallback path
if runtime.GOOS == "windows" {
return "C:\\Program Files\\s-ui\\db"
}
return "/usr/local/s-ui/db"
}
dbFolderPath = filepath.Join(dir, "db")
}
return dbFolderPath
}
func GetDBPath() string {
return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName())
}
================================================
FILE: config/name
================================================
s-ui
================================================
FILE: config/version
================================================
1.4.0
================================================
FILE: core/box.go
================================================
package core
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/alireza0/s-ui/util/common"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
boxService "github.com/sagernet/sing-box/adapter/service"
"github.com/sagernet/sing-box/common/certificate"
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/common/taskmonitor"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/dns/transport/local"
"github.com/sagernet/sing-box/experimental"
"github.com/sagernet/sing-box/experimental/cachefile"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/route"
sbCommon "github.com/sagernet/sing/common"
F "github.com/sagernet/sing/common/format"
"github.com/sagernet/sing/common/ntp"
"github.com/sagernet/sing/service"
"github.com/sagernet/sing/service/pause"
)
var _ adapter.SimpleLifecycle = (*Box)(nil)
type Box struct {
createdAt time.Time
logFactory log.Factory
logger log.ContextLogger
network *route.NetworkManager
endpoint *endpoint.Manager
inbound *inbound.Manager
outbound *outbound.Manager
service *boxService.Manager
dnsTransport *dns.TransportManager
dnsRouter *dns.Router
connection *route.ConnectionManager
router *route.Router
internalService []adapter.LifecycleService
statsTracker *StatsTracker
connTracker *ConnTracker
done chan struct{}
}
type Options struct {
option.Options
Context context.Context
}
func Context(
ctx context.Context,
inboundRegistry adapter.InboundRegistry,
outboundRegistry adapter.OutboundRegistry,
endpointRegistry adapter.EndpointRegistry,
dnsTransportRegistry adapter.DNSTransportRegistry,
serviceRegistry adapter.ServiceRegistry,
) context.Context {
if service.FromContext[option.InboundOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.InboundRegistry](ctx) == nil {
ctx = service.ContextWith[option.InboundOptionsRegistry](ctx, inboundRegistry)
ctx = service.ContextWith[adapter.InboundRegistry](ctx, inboundRegistry)
}
if service.FromContext[option.OutboundOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.OutboundRegistry](ctx) == nil {
ctx = service.ContextWith[option.OutboundOptionsRegistry](ctx, outboundRegistry)
ctx = service.ContextWith[adapter.OutboundRegistry](ctx, outboundRegistry)
}
if service.FromContext[option.EndpointOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.EndpointRegistry](ctx) == nil {
ctx = service.ContextWith[option.EndpointOptionsRegistry](ctx, endpointRegistry)
ctx = service.ContextWith[adapter.EndpointRegistry](ctx, endpointRegistry)
}
if service.FromContext[adapter.DNSTransportRegistry](ctx) == nil {
ctx = service.ContextWith[option.DNSTransportOptionsRegistry](ctx, dnsTransportRegistry)
ctx = service.ContextWith[adapter.DNSTransportRegistry](ctx, dnsTransportRegistry)
}
if service.FromContext[adapter.ServiceRegistry](ctx) == nil {
ctx = service.ContextWith[option.ServiceOptionsRegistry](ctx, serviceRegistry)
ctx = service.ContextWith[adapter.ServiceRegistry](ctx, serviceRegistry)
}
return ctx
}
func NewBox(options Options) (*Box, error) {
var err error
createdAt := time.Now()
ctx := options.Context
if ctx == nil {
ctx = context.Background()
}
ctx = service.ContextWithDefaultRegistry(ctx)
endpointRegistry := service.FromContext[adapter.EndpointRegistry](ctx)
inboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)
outboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)
dnsTransportRegistry := service.FromContext[adapter.DNSTransportRegistry](ctx)
serviceRegistry := service.FromContext[adapter.ServiceRegistry](ctx)
if endpointRegistry == nil {
return nil, common.NewError("missing endpoint registry in context")
}
if inboundRegistry == nil {
return nil, common.NewError("missing inbound registry in context")
}
if outboundRegistry == nil {
return nil, common.NewError("missing outbound registry in context")
}
if dnsTransportRegistry == nil {
return nil, common.NewError("missing DNS transport registry in context")
}
if serviceRegistry == nil {
return nil, common.NewError("missing service registry in context")
}
ctx = pause.WithDefaultManager(ctx)
experimentalOptions := sbCommon.PtrValueOrDefault(options.Experimental)
var needCacheFile bool
var needClashAPI bool
var needV2RayAPI bool
if experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled {
needCacheFile = true
}
if experimentalOptions.ClashAPI != nil {
needClashAPI = true
}
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
needV2RayAPI = true
}
platformInterface := service.FromContext[adapter.PlatformInterface](ctx)
var defaultLogWriter io.Writer
if platformInterface != nil {
defaultLogWriter = io.Discard
}
var logFactory log.Factory
logFactory, err = NewFactory(log.Options{
Context: ctx,
Options: sbCommon.PtrValueOrDefault(options.Log),
DefaultWriter: defaultLogWriter,
BaseTime: createdAt,
})
if err != nil {
return nil, common.NewError("create log factory", err)
}
factory = logFactory
var internalServices []adapter.LifecycleService
certificateOptions := sbCommon.PtrValueOrDefault(options.Certificate)
if C.IsAndroid || certificateOptions.Store != "" && certificateOptions.Store != C.CertificateStoreSystem ||
len(certificateOptions.Certificate) > 0 ||
len(certificateOptions.CertificatePath) > 0 ||
len(certificateOptions.CertificateDirectoryPath) > 0 {
certificateStore, err := certificate.NewStore(ctx, logFactory.NewLogger("certificate"), certificateOptions)
if err != nil {
return nil, err
}
service.MustRegister[adapter.CertificateStore](ctx, certificateStore)
internalServices = append(internalServices, certificateStore)
}
routeOptions := sbCommon.PtrValueOrDefault(options.Route)
dnsOptions := sbCommon.PtrValueOrDefault(options.DNS)
endpointManager := endpoint.NewManager(logFactory.NewLogger("endpoint"), endpointRegistry)
inboundManager := inbound.NewManager(logFactory.NewLogger("inbound"), inboundRegistry, endpointManager)
outboundManager := outbound.NewManager(logFactory.NewLogger("outbound"), outboundRegistry, endpointManager, routeOptions.Final)
dnsTransportManager := dns.NewTransportManager(logFactory.NewLogger("dns/transport"), dnsTransportRegistry, outboundManager, dnsOptions.Final)
serviceManager := boxService.NewManager(logFactory.NewLogger("service"), serviceRegistry)
service.MustRegister[adapter.EndpointManager](ctx, endpointManager)
service.MustRegister[adapter.InboundManager](ctx, inboundManager)
service.MustRegister[adapter.OutboundManager](ctx, outboundManager)
service.MustRegister[adapter.DNSTransportManager](ctx, dnsTransportManager)
service.MustRegister[adapter.ServiceManager](ctx, serviceManager)
dnsRouter := dns.NewRouter(ctx, logFactory, dnsOptions)
service.MustRegister[adapter.DNSRouter](ctx, dnsRouter)
networkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger("network"), routeOptions, dnsOptions)
if err != nil {
return nil, common.NewError("initialize network manager", err)
}
service.MustRegister[adapter.NetworkManager](ctx, networkManager)
connectionManager := route.NewConnectionManager(logFactory.NewLogger("connection"))
service.MustRegister[adapter.ConnectionManager](ctx, connectionManager)
router := route.NewRouter(ctx, logFactory, routeOptions, dnsOptions)
service.MustRegister[adapter.Router](ctx, router)
err = router.Initialize(routeOptions.Rules, routeOptions.RuleSet)
if err != nil {
return nil, common.NewError("initialize router", err)
}
for i, transportOptions := range dnsOptions.Servers {
var tag string
if transportOptions.Tag != "" {
tag = transportOptions.Tag
} else {
tag = F.ToString(i)
}
err = dnsTransportManager.Create(
ctx,
logFactory.NewLogger(F.ToString("dns/", transportOptions.Type, "[", tag, "]")),
tag,
transportOptions.Type,
transportOptions.Options,
)
if err != nil {
return nil, common.NewError("initialize DNS server[", i, "]", err)
}
}
err = dnsRouter.Initialize(dnsOptions.Rules)
if err != nil {
return nil, common.NewError("initialize dns router", err)
}
for i, endpointOptions := range options.Endpoints {
var tag string
if endpointOptions.Tag != "" {
tag = endpointOptions.Tag
} else {
tag = F.ToString(i)
}
err = endpointManager.Create(
ctx,
router,
logFactory.NewLogger(F.ToString("endpoint/", endpointOptions.Type, "[", tag, "]")),
tag,
endpointOptions.Type,
endpointOptions.Options,
)
if err != nil {
return nil, common.NewError("initialize endpoint["+F.ToString(i)+"] "+tag, err)
}
}
for i, inboundOptions := range options.Inbounds {
var tag string
if inboundOptions.Tag != "" {
tag = inboundOptions.Tag
} else {
tag = F.ToString(i)
}
err = inboundManager.Create(
ctx,
router,
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
tag,
inboundOptions.Type,
inboundOptions.Options,
)
if err != nil {
return nil, common.NewError("initialize inbound[", i, "] ", tag, err)
}
}
for i, outboundOptions := range options.Outbounds {
var tag string
if outboundOptions.Tag != "" {
tag = outboundOptions.Tag
} else {
tag = F.ToString(i)
}
outboundCtx := ctx
if tag != "" {
// TODO: remove this
outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
Outbound: tag,
})
}
err = outboundManager.Create(
outboundCtx,
router,
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
tag,
outboundOptions.Type,
outboundOptions.Options,
)
if err != nil {
return nil, common.NewError("initialize outbound["+F.ToString(i)+"] "+tag, err)
}
}
for i, serviceOptions := range options.Services {
var tag string
if serviceOptions.Tag != "" {
tag = serviceOptions.Tag
} else {
tag = F.ToString(i)
}
err = serviceManager.Create(
ctx,
logFactory.NewLogger(F.ToString("service/", serviceOptions.Type, "[", tag, "]")),
tag,
serviceOptions.Type,
serviceOptions.Options,
)
if err != nil {
return nil, common.NewError("initialize service["+F.ToString(i)+"]"+tag, err)
}
}
outboundManager.Initialize(func() (adapter.Outbound, error) {
return direct.NewOutbound(
ctx,
router,
logFactory.NewLogger("outbound/direct"),
"direct",
option.DirectOutboundOptions{},
)
})
dnsTransportManager.Initialize(func() (adapter.DNSTransport, error) {
return local.NewTransport(
ctx,
logFactory.NewLogger("dns/local"),
"local",
option.LocalDNSServerOptions{},
)
})
if platformInterface != nil {
err = platformInterface.Initialize(networkManager)
if err != nil {
return nil, common.NewError("initialize platform interface", err)
}
}
if statsTracker == nil {
statsTracker = NewStatsTracker()
}
router.AppendTracker(statsTracker)
if connTracker == nil {
connTracker = NewConnTracker()
}
router.AppendTracker(connTracker)
if needCacheFile {
cacheFile := cachefile.New(ctx, sbCommon.PtrValueOrDefault(experimentalOptions.CacheFile))
service.MustRegister[adapter.CacheFile](ctx, cacheFile)
internalServices = append(internalServices, cacheFile)
}
if needClashAPI {
clashAPIOptions := sbCommon.PtrValueOrDefault(experimentalOptions.ClashAPI)
clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
clashServer, err := experimental.NewClashServer(ctx, logFactory.(log.ObservableFactory), clashAPIOptions)
if err != nil {
return nil, common.NewError(err, "create clash-server")
}
router.AppendTracker(clashServer)
service.MustRegister[adapter.ClashServer](ctx, clashServer)
internalServices = append(internalServices, clashServer)
}
if needV2RayAPI {
v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), sbCommon.PtrValueOrDefault(experimentalOptions.V2RayAPI))
if err != nil {
return nil, common.NewError(err, "create v2ray-server")
}
if v2rayServer.StatsService() != nil {
router.AppendTracker(v2rayServer.StatsService())
internalServices = append(internalServices, v2rayServer)
service.MustRegister[adapter.V2RayServer](ctx, v2rayServer)
}
}
ntpOptions := sbCommon.PtrValueOrDefault(options.NTP)
if ntpOptions.Enabled {
ntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions, ntpOptions.ServerIsDomain())
if err != nil {
return nil, common.NewError(err, "create NTP service")
}
timeService := ntp.NewService(ntp.Options{
Context: ctx,
Dialer: ntpDialer,
Logger: logFactory.NewLogger("ntp"),
Server: ntpOptions.ServerOptions.Build(),
Interval: time.Duration(ntpOptions.Interval),
WriteToSystem: ntpOptions.WriteToSystem,
})
service.MustRegister[ntp.TimeService](ctx, timeService)
internalServices = append(internalServices, adapter.NewLifecycleService(timeService, "ntp service"))
}
return &Box{
network: networkManager,
endpoint: endpointManager,
inbound: inboundManager,
outbound: outboundManager,
dnsTransport: dnsTransportManager,
service: serviceManager,
dnsRouter: dnsRouter,
connection: connectionManager,
router: router,
createdAt: createdAt,
logFactory: logFactory,
logger: logFactory.Logger(),
internalService: internalServices,
statsTracker: statsTracker,
connTracker: connTracker,
done: make(chan struct{}),
}, nil
}
func (s *Box) PreStart() error {
err := s.preStart()
if err != nil {
// TODO: remove catch error
defer func() {
v := recover()
if v != nil {
s.logger.Error(err.Error())
s.logger.Error("panic on early close: " + fmt.Sprint(v))
}
}()
s.Close()
return err
}
s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil
}
func (s *Box) Start() error {
err := s.start()
if err != nil {
return err
}
s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil
}
func (s *Box) preStart() error {
monitor := taskmonitor.New(s.logger, C.StartTimeout)
monitor.Start("start logger")
err := s.logFactory.Start()
monitor.Finish()
if err != nil {
return common.NewError(err, "start logger")
}
err = adapter.StartNamed(s.logger, adapter.StartStateInitialize, s.internalService) // cache-file clash-api v2ray-api
if err != nil {
return err
}
err = adapter.Start(s.logger, adapter.StartStateInitialize, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint, s.service)
if err != nil {
return err
}
err = adapter.Start(s.logger, adapter.StartStateStart, s.outbound, s.dnsTransport, s.dnsRouter, s.network, s.connection, s.router)
if err != nil {
return err
}
return nil
}
func (s *Box) start() error {
err := s.preStart()
if err != nil {
return err
}
err = adapter.StartNamed(s.logger, adapter.StartStateStart, s.internalService)
if err != nil {
return err
}
err = adapter.Start(s.logger, adapter.StartStateStart, s.inbound, s.endpoint, s.service)
if err != nil {
return err
}
err = adapter.Start(s.logger, adapter.StartStatePostStart, s.outbound, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.inbound, s.endpoint, s.service)
if err != nil {
return err
}
err = adapter.StartNamed(s.logger, adapter.StartStatePostStart, s.internalService)
if err != nil {
return err
}
err = adapter.Start(s.logger, adapter.StartStateStarted, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint, s.service)
if err != nil {
return err
}
err = adapter.StartNamed(s.logger, adapter.StartStateStarted, s.internalService)
if err != nil {
return err
}
return nil
}
func (s *Box) Close() error {
select {
case <-s.done:
return nil
default:
close(s.done)
}
var err error
s.logger.Info("closing sing-box")
for _, closeItem := range []struct {
name string
service adapter.Lifecycle
}{
{"service", s.service},
{"endpoint", s.endpoint},
{"inbound", s.inbound},
{"outbound", s.outbound},
{"router", s.router},
{"connection", s.connection},
{"dns-router", s.dnsRouter},
{"dns-transport", s.dnsTransport},
{"network", s.network},
} {
if closeItem.service == nil {
continue
}
func() {
defer func() {
if v := recover(); v != nil {
err = errors.Join(err, common.NewError(fmt.Errorf("panic: %v", v), "close "+closeItem.name))
s.logger.Error("panic closing ", closeItem.name, ": ", v)
}
}()
s.logger.Trace("close ", closeItem.name)
startTime := time.Now()
closeErr := closeItem.service.Close()
if closeErr != nil {
closeErr = common.NewError(closeErr, "close "+closeItem.name)
}
err = errors.Join(err, closeErr)
s.logger.Trace("close ", closeItem.name, " completed (", F.Seconds(time.Since(startTime).Seconds()), "s)")
}()
}
for _, lifecycleService := range s.internalService {
if lifecycleService == nil {
continue
}
func() {
defer func() {
if v := recover(); v != nil {
err = errors.Join(err, common.NewError(fmt.Errorf("panic: %v", v), "close "+lifecycleService.Name()))
s.logger.Error("panic closing ", lifecycleService.Name(), ": ", v)
}
}()
s.logger.Trace("close ", lifecycleService.Name())
startTime := time.Now()
closeErr := lifecycleService.Close()
if closeErr != nil {
closeErr = common.NewError(closeErr, "close "+lifecycleService.Name())
}
err = errors.Join(err, closeErr)
s.logger.Trace("close ", lifecycleService.Name(), " completed (", F.Seconds(time.Since(startTime).Seconds()), "s)")
}()
}
s.logger.Trace("close logger")
startTime := time.Now()
closeErr := s.logFactory.Close()
if closeErr != nil {
closeErr = common.NewError(closeErr, "close logger")
}
err = errors.Join(err, closeErr)
s.logger.Trace("close logger completed (", F.Seconds(time.Since(startTime).Seconds()), "s)")
s.logger.Info("sing-box closed (live time: ", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return err
}
func (s *Box) Uptime() uint32 {
return uint32(time.Now().Sub(s.createdAt).Seconds())
}
func (s *Box) Network() adapter.NetworkManager {
return s.network
}
func (s *Box) Router() adapter.Router {
return s.router
}
func (s *Box) Inbound() adapter.InboundManager {
return s.inbound
}
func (s *Box) Outbound() adapter.OutboundManager {
return s.outbound
}
func (s *Box) Endpoint() adapter.EndpointManager {
return s.endpoint
}
func (s *Box) StatsTracker() *StatsTracker {
return s.statsTracker
}
func (s *Box) ConnTracker() *ConnTracker {
return s.connTracker
}
================================================
FILE: core/endpoint.go
================================================
package core
import (
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/util/common"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
)
func (c *Core) AddInbound(config []byte) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
var err error
var inbound_config option.Inbound
err = inbound_config.UnmarshalJSONContext(c.GetCtx(), config)
if err != nil {
return err
}
err = inbound_manager.Create(
c.GetCtx(),
router,
factory.NewLogger("inbound/"+inbound_config.Type+"["+inbound_config.Tag+"]"),
inbound_config.Tag,
inbound_config.Type,
inbound_config.Options)
if err != nil {
return err
}
return nil
}
func (c *Core) RemoveInbound(tag string) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
logger.Info("remove inbound: ", tag)
return inbound_manager.Remove(tag)
}
func (c *Core) AddOutbound(config []byte) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
var err error
var outbound_config option.Outbound
err = outbound_config.UnmarshalJSONContext(c.GetCtx(), config)
if err != nil {
return err
}
outboundCtx := adapter.WithContext(c.GetCtx(), &adapter.InboundContext{
Outbound: outbound_config.Tag,
})
err = outbound_manager.Create(
outboundCtx,
router,
factory.NewLogger("outbound/"+outbound_config.Type+"["+outbound_config.Tag+"]"),
outbound_config.Tag,
outbound_config.Type,
outbound_config.Options)
if err != nil {
return err
}
return nil
}
func (c *Core) RemoveOutbound(tag string) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
logger.Info("remove outbound: ", tag)
return outbound_manager.Remove(tag)
}
func (c *Core) AddEndpoint(config []byte) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
var err error
var endpoint_config option.Endpoint
err = endpoint_config.UnmarshalJSONContext(c.GetCtx(), config)
if err != nil {
return err
}
err = endpoint_manager.Create(
c.GetCtx(),
router,
factory.NewLogger("endpoint/"+endpoint_config.Type+"["+endpoint_config.Tag+"]"),
endpoint_config.Tag,
endpoint_config.Type,
endpoint_config.Options)
if err != nil {
return err
}
return nil
}
func (c *Core) RemoveEndpoint(tag string) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
logger.Info("remove endpoint: ", tag)
return endpoint_manager.Remove(tag)
}
func (c *Core) AddService(config []byte) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
var err error
var srv_config option.Service
err = srv_config.UnmarshalJSONContext(c.GetCtx(), config)
if err != nil {
return err
}
err = service_manager.Create(
c.GetCtx(),
factory.NewLogger("service/"+srv_config.Type+"["+srv_config.Tag+"]"),
srv_config.Tag,
srv_config.Type,
srv_config.Options)
if err != nil {
return err
}
return nil
}
func (c *Core) RemoveService(tag string) error {
if !c.isRunning {
return common.NewError("sing-box is not running")
}
logger.Info("remove service: ", tag)
return service_manager.Remove(tag)
}
================================================
FILE: core/log.go
================================================
package core
import (
"context"
"io"
"os"
"time"
suiLog "github.com/alireza0/s-ui/logger"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
F "github.com/sagernet/sing/common/format"
"github.com/sagernet/sing/common/observable"
"github.com/sagernet/sing/service/filemanager"
)
type PlatformWriter struct{}
func (p PlatformWriter) DisableColors() bool {
return true
}
func (p PlatformWriter) WriteMessage(level log.Level, message string) {
switch level {
case log.LevelInfo:
suiLog.Info(message)
case log.LevelWarn:
suiLog.Warning(message)
case log.LevelPanic:
case log.LevelFatal:
case log.LevelError:
suiLog.Error(message)
default:
suiLog.Debug(message)
}
}
func NewFactory(options log.Options) (log.Factory, error) {
logOptions := options.Options
if logOptions.Disabled {
return log.NewNOPFactory(), nil
}
var logWriter io.Writer
var logFilePath string
switch logOptions.Output {
case "":
logWriter = options.DefaultWriter
if logWriter == nil {
logWriter = os.Stderr
}
case "stderr":
logWriter = os.Stderr
case "stdout":
logWriter = os.Stdout
default:
logFilePath = logOptions.Output
}
logFormatter := log.Formatter{
BaseTime: options.BaseTime,
DisableColors: logOptions.DisableColor || logFilePath != "",
DisableTimestamp: !logOptions.Timestamp && logFilePath != "",
FullTimestamp: logOptions.Timestamp,
TimestampFormat: "-0700 2006-01-02 15:04:05",
}
factory := NewDefaultFactory(
options.Context,
logFormatter,
logWriter,
logFilePath,
)
if logOptions.Level != "" {
logLevel, err := log.ParseLevel(logOptions.Level)
if err != nil {
return nil, common.Error("parse log level", err)
}
factory.SetLevel(logLevel)
} else {
factory.SetLevel(log.LevelTrace)
}
return factory, nil
}
var _ log.Factory = (*defaultFactory)(nil)
type defaultFactory struct {
ctx context.Context
formatter log.Formatter
writer io.Writer
file *os.File
filePath string
level log.Level
subscriber *observable.Subscriber[log.Entry]
observer *observable.Observer[log.Entry]
}
func NewDefaultFactory(
ctx context.Context,
formatter log.Formatter,
writer io.Writer,
filePath string,
) log.ObservableFactory {
factory := &defaultFactory{
ctx: ctx,
formatter: formatter,
writer: writer,
filePath: filePath,
level: log.LevelTrace,
subscriber: observable.NewSubscriber[log.Entry](128),
}
return factory
}
func (f *defaultFactory) Start() error {
if f.filePath != "" {
logFile, err := filemanager.OpenFile(f.ctx, f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return err
}
f.writer = logFile
f.file = logFile
}
return nil
}
func (f *defaultFactory) Close() error {
return common.Close(
common.PtrOrNil(f.file),
f.subscriber,
)
}
func (f *defaultFactory) Level() log.Level {
return f.level
}
func (f *defaultFactory) SetLevel(level log.Level) {
f.level = level
}
func (f *defaultFactory) Logger() log.ContextLogger {
return f.NewLogger("")
}
func (f *defaultFactory) NewLogger(tag string) log.ContextLogger {
return &observableLogger{f, tag}
}
func (f *defaultFactory) Subscribe() (subscription observable.Subscription[log.Entry], done <-chan struct{}, err error) {
return f.observer.Subscribe()
}
func (f *defaultFactory) UnSubscribe(sub observable.Subscription[log.Entry]) {
f.observer.UnSubscribe(sub)
}
type observableLogger struct {
*defaultFactory
tag string
}
func (l *observableLogger) Log(ctx context.Context, level log.Level, args []any) {
level = log.OverrideLevelFromContext(level, ctx)
if level > l.level {
return
}
msg := F.ToString(args...)
switch level {
case log.LevelInfo:
suiLog.Info(l.tag, msg)
case log.LevelWarn:
suiLog.Warning(l.tag, msg)
case log.LevelPanic:
case log.LevelFatal:
case log.LevelError:
suiLog.Error(l.tag, msg)
default:
suiLog.Debug(l.tag, msg)
}
if (l.filePath != "" || l.writer != os.Stderr) && l.writer != nil {
message := l.formatter.Format(ctx, level, l.tag, msg, time.Now())
l.writer.Write([]byte(message))
}
}
func (l *observableLogger) Trace(args ...any) {
l.TraceContext(context.Background(), args...)
}
func (l *observableLogger) Debug(args ...any) {
l.DebugContext(context.Background(), args...)
}
func (l *observableLogger) Info(args ...any) {
l.InfoContext(context.Background(), args...)
}
func (l *observableLogger) Warn(args ...any) {
l.WarnContext(context.Background(), args...)
}
func (l *observableLogger) Error(args ...any) {
l.ErrorContext(context.Background(), args...)
}
func (l *observableLogger) Fatal(args ...any) {
l.FatalContext(context.Background(), args...)
}
func (l *observableLogger) Panic(args ...any) {
l.PanicContext(context.Background(), args...)
}
func (l *observableLogger) TraceContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelTrace, args)
}
func (l *observableLogger) DebugContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelDebug, args)
}
func (l *observableLogger) InfoContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelInfo, args)
}
func (l *observableLogger) WarnContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelWarn, args)
}
func (l *observableLogger) ErrorContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelError, args)
}
func (l *observableLogger) FatalContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelFatal, args)
}
func (l *observableLogger) PanicContext(ctx context.Context, args ...any) {
l.Log(ctx, log.LevelPanic, args)
}
================================================
FILE: core/main.go
================================================
package core
import (
"context"
"github.com/alireza0/s-ui/logger"
sb "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/adapter"
_ "github.com/sagernet/sing-box/experimental/clashapi"
_ "github.com/sagernet/sing-box/experimental/v2rayapi"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
_ "github.com/sagernet/sing-box/transport/v2rayquic"
"github.com/sagernet/sing/service"
)
var (
globalCtx context.Context
inbound_manager adapter.InboundManager
outbound_manager adapter.OutboundManager
service_manager adapter.ServiceManager
endpoint_manager adapter.EndpointManager
router adapter.Router
statsTracker *StatsTracker
connTracker *ConnTracker
factory log.Factory
)
type Core struct {
isRunning bool
instance *Box
}
func NewCore() *Core {
globalCtx = context.Background()
globalCtx = sb.Context(globalCtx, InboundRegistry(), OutboundRegistry(), EndpointRegistry(), DNSTransportRegistry(), ServiceRegistry())
return &Core{
isRunning: false,
instance: nil,
}
}
func (c *Core) GetCtx() context.Context {
return globalCtx
}
func (c *Core) GetInstance() *Box {
return c.instance
}
func (c *Core) Start(sbConfig []byte) error {
var opt option.Options
err := opt.UnmarshalJSONContext(globalCtx, sbConfig)
if err != nil {
logger.Error("Unmarshal config err:", err.Error())
}
c.instance, err = NewBox(Options{
Context: globalCtx,
Options: opt,
})
if err != nil {
return err
}
err = c.instance.Start()
if err != nil {
_ = c.instance.Close()
c.instance = nil
return err
}
globalCtx = service.ContextWith(globalCtx, c)
inbound_manager = service.FromContext[adapter.InboundManager](globalCtx)
outbound_manager = service.FromContext[adapter.OutboundManager](globalCtx)
service_manager = service.FromContext[adapter.ServiceManager](globalCtx)
endpoint_manager = service.FromContext[adapter.EndpointManager](globalCtx)
router = service.FromContext[adapter.Router](globalCtx)
c.isRunning = true
return nil
}
func (c *Core) Stop() error {
c.isRunning = false
if c.instance == nil {
return nil
}
err := c.instance.Close()
c.instance = nil
return err
}
func (c *Core) IsRunning() bool {
return c.isRunning
}
================================================
FILE: core/outbound_check.go
================================================
package core
import (
"context"
"time"
urltest "github.com/sagernet/sing-box/common/urltest"
)
const checkTimeout = 15 * time.Second
type CheckOutboundResult struct {
OK bool
Delay uint16
Error string
}
func CheckOutbound(ctx context.Context, tag string, link string) (result CheckOutboundResult) {
if outbound_manager == nil {
result.Error = "core not running"
return result
}
ob, ok := outbound_manager.Outbound(tag)
if !ok {
result.Error = "outbound not found"
return result
}
ctx, cancel := context.WithTimeout(ctx, checkTimeout)
defer cancel()
delay, err := urltest.URLTest(ctx, link, ob)
if err != nil {
result.Error = err.Error()
return result
}
result.OK = true
result.Delay = delay
return result
}
================================================
FILE: core/register.go
================================================
package core
import (
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/adapter/service"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/dns/transport"
"github.com/sagernet/sing-box/dns/transport/dhcp"
"github.com/sagernet/sing-box/dns/transport/fakeip"
"github.com/sagernet/sing-box/dns/transport/hosts"
"github.com/sagernet/sing-box/dns/transport/local"
"github.com/sagernet/sing-box/dns/transport/quic"
"github.com/sagernet/sing-box/protocol/anytls"
"github.com/sagernet/sing-box/protocol/block"
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/protocol/group"
"github.com/sagernet/sing-box/protocol/http"
"github.com/sagernet/sing-box/protocol/hysteria"
"github.com/sagernet/sing-box/protocol/hysteria2"
"github.com/sagernet/sing-box/protocol/mixed"
"github.com/sagernet/sing-box/protocol/naive"
_ "github.com/sagernet/sing-box/protocol/naive/quic"
"github.com/sagernet/sing-box/protocol/redirect"
"github.com/sagernet/sing-box/protocol/shadowsocks"
"github.com/sagernet/sing-box/protocol/shadowtls"
"github.com/sagernet/sing-box/protocol/socks"
"github.com/sagernet/sing-box/protocol/ssh"
"github.com/sagernet/sing-box/protocol/tailscale"
"github.com/sagernet/sing-box/protocol/tor"
"github.com/sagernet/sing-box/protocol/trojan"
"github.com/sagernet/sing-box/protocol/tuic"
"github.com/sagernet/sing-box/protocol/tun"
"github.com/sagernet/sing-box/protocol/vless"
"github.com/sagernet/sing-box/protocol/vmess"
"github.com/sagernet/sing-box/protocol/wireguard"
"github.com/sagernet/sing-box/service/ccm"
"github.com/sagernet/sing-box/service/derp"
"github.com/sagernet/sing-box/service/ocm"
"github.com/sagernet/sing-box/service/resolved"
"github.com/sagernet/sing-box/service/ssmapi"
_ "github.com/sagernet/sing-box/transport/v2rayquic"
)
func InboundRegistry() *inbound.Registry {
registry := inbound.NewRegistry()
tun.RegisterInbound(registry)
redirect.RegisterRedirect(registry)
redirect.RegisterTProxy(registry)
direct.RegisterInbound(registry)
socks.RegisterInbound(registry)
http.RegisterInbound(registry)
mixed.RegisterInbound(registry)
shadowsocks.RegisterInbound(registry)
vmess.RegisterInbound(registry)
trojan.RegisterInbound(registry)
naive.RegisterInbound(registry)
shadowtls.RegisterInbound(registry)
vless.RegisterInbound(registry)
anytls.RegisterInbound(registry)
hysteria.RegisterInbound(registry)
tuic.RegisterInbound(registry)
hysteria2.RegisterInbound(registry)
return registry
}
func OutboundRegistry() *outbound.Registry {
registry := outbound.NewRegistry()
direct.RegisterOutbound(registry)
block.RegisterOutbound(registry)
group.RegisterSelector(registry)
group.RegisterURLTest(registry)
socks.RegisterOutbound(registry)
http.RegisterOutbound(registry)
shadowsocks.RegisterOutbound(registry)
vmess.RegisterOutbound(registry)
trojan.RegisterOutbound(registry)
registerNaiveOutbound(registry)
tor.RegisterOutbound(registry)
ssh.RegisterOutbound(registry)
shadowtls.RegisterOutbound(registry)
vless.RegisterOutbound(registry)
anytls.RegisterOutbound(registry)
hysteria.RegisterOutbound(registry)
tuic.RegisterOutbound(registry)
hysteria2.RegisterOutbound(registry)
return registry
}
func EndpointRegistry() *endpoint.Registry {
registry := endpoint.NewRegistry()
wireguard.RegisterEndpoint(registry)
tailscale.RegisterEndpoint(registry)
return registry
}
func DNSTransportRegistry() *dns.TransportRegistry {
registry := dns.NewTransportRegistry()
transport.RegisterTCP(registry)
transport.RegisterUDP(registry)
transport.RegisterTLS(registry)
transport.RegisterHTTPS(registry)
hosts.RegisterTransport(registry)
local.RegisterTransport(registry)
fakeip.RegisterTransport(registry)
quic.RegisterTransport(registry)
quic.RegisterHTTP3Transport(registry)
dhcp.RegisterTransport(registry)
tailscale.RegistryTransport(registry)
return registry
}
func ServiceRegistry() *service.Registry {
registry := service.NewRegistry()
resolved.RegisterService(registry)
ssmapi.RegisterService(registry)
derp.Register(registry)
ccm.RegisterService(registry)
ocm.RegisterService(registry)
return registry
}
================================================
FILE: core/register_naive.go
================================================
//go:build with_naive_outbound
package core
import (
"github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/protocol/naive"
)
func registerNaiveOutbound(registry *outbound.Registry) {
naive.RegisterOutbound(registry)
}
================================================
FILE: core/register_naive_stub.go
================================================
//go:build !with_naive_outbound
package core
import (
"github.com/alireza0/s-ui/logger"
"github.com/sagernet/sing-box/adapter/outbound"
)
func registerNaiveOutbound(registry *outbound.Registry) {
// naive outbound is disabled when built without with_naive_outbound tag
logger.Error("naive outbound is disabled when built without with_naive_outbound tag")
}
================================================
FILE: core/tracker_conn.go
================================================
package core
import (
"context"
"net"
"sync"
"github.com/gofrs/uuid/v5"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common/network"
)
type ConnectionInfo struct {
ID string
Conn net.Conn
PacketConn network.PacketConn
Inbound string
Type string // "tcp" or "udp"
}
type ConnTracker struct {
access sync.Mutex
connections map[string]*ConnectionInfo
}
func NewConnTracker() *ConnTracker {
return &ConnTracker{
connections: make(map[string]*ConnectionInfo),
}
}
func (c *ConnTracker) generateConnectionID() string {
return uuid.Must(uuid.NewV4()).String()
}
func (c *ConnTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn {
connID := c.generateConnectionID()
connInfo := &ConnectionInfo{
ID: connID,
Conn: conn,
Inbound: metadata.Inbound,
Type: "tcp",
}
c.trackConnection(connID, connInfo)
return c.createWrappedConn(conn, connID)
}
func (c *ConnTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn {
connID := c.generateConnectionID()
connInfo := &ConnectionInfo{
ID: connID,
PacketConn: conn,
Inbound: metadata.Inbound,
Type: "udp",
}
c.trackConnection(connID, connInfo)
return c.createWrappedPacketConn(conn, connID)
}
func (c *ConnTracker) CloseConnByInbound(inbound string) int {
c.access.Lock()
defer c.access.Unlock()
closedCount := 0
for connID, connInfo := range c.connections {
if connInfo.Inbound == inbound {
if connInfo.Conn != nil {
connInfo.Conn.Close()
}
if connInfo.PacketConn != nil {
connInfo.PacketConn.Close()
}
delete(c.connections, connID)
closedCount++
}
}
return closedCount
}
func (c *ConnTracker) trackConnection(connID string, connInfo *ConnectionInfo) {
c.access.Lock()
defer c.access.Unlock()
c.connections[connID] = connInfo
}
func (c *ConnTracker) untrackConnection(connID string) {
c.access.Lock()
defer c.access.Unlock()
delete(c.connections, connID)
}
func (c *ConnTracker) createWrappedConn(conn net.Conn, connID string) *wrappedConn {
return &wrappedConn{
Conn: conn,
connID: connID,
}
}
func (c *ConnTracker) createWrappedPacketConn(conn network.PacketConn, connID string) *wrappedPacketConn {
return &wrappedPacketConn{
PacketConn: conn,
connID: connID,
}
}
type wrappedConn struct {
net.Conn
connID string
}
func (w *wrappedConn) Close() error {
connTracker.untrackConnection(w.connID)
return w.Conn.Close()
}
func (w *wrappedConn) Upstream() any {
return w.Conn
}
type wrappedPacketConn struct {
network.PacketConn
connID string
}
func (w *wrappedPacketConn) Close() error {
connTracker.untrackConnection(w.connID)
return w.PacketConn.Close()
}
func (w *wrappedPacketConn) Upstream() any {
return w.PacketConn
}
================================================
FILE: core/tracker_stats.go
================================================
package core
import (
"context"
"net"
"sync"
"time"
"github.com/alireza0/s-ui/database/model"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common/atomic"
"github.com/sagernet/sing/common/bufio"
"github.com/sagernet/sing/common/network"
)
type Counter struct {
read *atomic.Int64
write *atomic.Int64
}
type StatsTracker struct {
access sync.Mutex
inbounds map[string]Counter
outbounds map[string]Counter
users map[string]Counter
}
func NewStatsTracker() *StatsTracker {
return &StatsTracker{
inbounds: make(map[string]Counter),
outbounds: make(map[string]Counter),
users: make(map[string]Counter),
}
}
func (c *StatsTracker) getReadCounters(inbound string, outbound string, user string) ([]*atomic.Int64, []*atomic.Int64) {
var readCounter []*atomic.Int64
var writeCounter []*atomic.Int64
c.access.Lock()
defer c.access.Unlock()
if inbound != "" {
readCounter = append(readCounter, c.loadOrCreateCounter(&c.inbounds, inbound).read)
writeCounter = append(writeCounter, c.inbounds[inbound].write)
}
if outbound != "" {
readCounter = append(readCounter, c.loadOrCreateCounter(&c.outbounds, outbound).read)
writeCounter = append(writeCounter, c.outbounds[outbound].write)
}
if user != "" {
readCounter = append(readCounter, c.loadOrCreateCounter(&c.users, user).read)
writeCounter = append(writeCounter, c.users[user].write)
}
return readCounter, writeCounter
}
func (c *StatsTracker) loadOrCreateCounter(obj *map[string]Counter, name string) Counter {
counter, loaded := (*obj)[name]
if loaded {
return counter
}
counter = Counter{read: &atomic.Int64{}, write: &atomic.Int64{}}
(*obj)[name] = counter
return counter
}
func (c *StatsTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn {
readCounter, writeCounter := c.getReadCounters(metadata.Inbound, matchOutbound.Tag(), metadata.User)
return bufio.NewInt64CounterConn(conn, readCounter, writeCounter)
}
func (c *StatsTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn {
readCounter, writeCounter := c.getReadCounters(metadata.Inbound, matchOutbound.Tag(), metadata.User)
return bufio.NewInt64CounterPacketConn(conn, readCounter, nil, writeCounter, nil)
}
func (c *StatsTracker) GetStats() *[]model.Stats {
c.access.Lock()
defer c.access.Unlock()
dt := time.Now().Unix()
s := []model.Stats{}
for inbound, counter := range c.inbounds {
down := counter.write.Swap(0)
up := counter.read.Swap(0)
if down > 0 || up > 0 {
s = append(s, model.Stats{
DateTime: dt,
Resource: "inbound",
Tag: inbound,
Direction: false,
Traffic: down,
}, model.Stats{
DateTime: dt,
Resource: "inbound",
Tag: inbound,
Direction: true,
Traffic: up,
})
}
}
for outbound, counter := range c.outbounds {
down := counter.write.Swap(0)
up := counter.read.Swap(0)
if down > 0 || up > 0 {
s = append(s, model.Stats{
DateTime: dt,
Resource: "outbound",
Tag: outbound,
Direction: false,
Traffic: down,
}, model.Stats{
DateTime: dt,
Resource: "outbound",
Tag: outbound,
Direction: true,
Traffic: up,
})
}
}
for user, counter := range c.users {
down := counter.write.Swap(0)
up := counter.read.Swap(0)
if down > 0 || up > 0 {
s = append(s, model.Stats{
DateTime: dt,
Resource: "user",
Tag: user,
Direction: false,
Traffic: down,
}, model.Stats{
DateTime: dt,
Resource: "user",
Tag: user,
Direction: true,
Traffic: up,
})
}
}
return &s
}
================================================
FILE: cronjob/WALCheckpointJob.go
================================================
package cronjob
import (
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/logger"
)
type WALCheckpointJob struct{}
func NewWALCheckpointJob() *WALCheckpointJob {
return &WALCheckpointJob{}
}
func (s *WALCheckpointJob) Run() {
db := database.GetDB()
_, err := db.Raw("PRAGMA wal_checkpoint(FULL)").Rows()
if err != nil {
logger.Error("Error checkpointing WAL: ", err.Error())
}
}
================================================
FILE: cronjob/checkCoreJob.go
================================================
package cronjob
import (
"github.com/alireza0/s-ui/service"
)
type CheckCoreJob struct {
service.ConfigService
}
func NewCheckCoreJob() *CheckCoreJob {
return &CheckCoreJob{}
}
func (s *CheckCoreJob) Run() {
s.ConfigService.StartCore()
}
================================================
FILE: cronjob/cronJob.go
================================================
package cronjob
import (
"time"
"github.com/robfig/cron/v3"
)
type CronJob struct {
cron *cron.Cron
}
func NewCronJob() *CronJob {
return &CronJob{}
}
func (c *CronJob) Start(loc *time.Location, trafficAge int) error {
c.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
c.cron.Start()
go func() {
// Start stats job
c.cron.AddJob("@every 10s", NewStatsJob(trafficAge > 0))
// Start expiry job
c.cron.AddJob("@every 1m", NewDepleteJob())
// Start deleting old stats
if trafficAge > 0 {
c.cron.AddJob("@daily", NewDelStatsJob(trafficAge))
}
// Start core if it is not running
c.cron.AddJob("@every 5s", NewCheckCoreJob())
// database WAL checkpoint
c.cron.AddJob("@every 10m", NewWALCheckpointJob())
}()
return nil
}
func (c *CronJob) Stop() {
if c.cron != nil {
c.cron.Stop()
}
}
================================================
FILE: cronjob/delStatsJob.go
================================================
package cronjob
import (
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/service"
)
type DelStatsJob struct {
service.StatsService
trafficAge int
}
func NewDelStatsJob(ta int) *DelStatsJob {
return &DelStatsJob{
trafficAge: ta,
}
}
func (s *DelStatsJob) Run() {
err := s.StatsService.DelOldStats(s.trafficAge)
if err != nil {
logger.Warning("Deleting old statistics failed: ", err)
return
}
logger.Debug("Stats older than ", s.trafficAge, " days were deleted")
}
================================================
FILE: cronjob/depleteJob.go
================================================
package cronjob
import (
"github.com/alireza0/s-ui/database"
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/service"
)
type DepleteJob struct {
service.ClientService
service.InboundService
}
func NewDepleteJob() *DepleteJob {
return new(DepleteJob)
}
func (s *DepleteJob) Run() {
inboundIds, err := s.ClientService.DepleteClients()
if err != nil {
logger.Warning("Disable depleted users failed: ", err)
return
}
if len(inboundIds) > 0 {
err := s.InboundService.RestartInbounds(database.GetDB(), inboundIds)
if err != nil {
logger.Error("unable to restart inbounds: ", err)
}
}
}
================================================
FILE: cronjob/statsJob.go
================================================
package cronjob
import (
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/service"
)
type StatsJob struct {
service.StatsService
enableTraffic bool
}
func NewStatsJob(saveTraffic bool) *StatsJob {
return &StatsJob{
enableTraffic: saveTraffic,
}
}
func (s *StatsJob) Run() {
err := s.StatsService.SaveStats(s.enableTraffic)
if err != nil {
logger.Warning("Get stats failed: ", err)
return
}
}
================================================
FILE: database/backup.go
================================================
package database
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/alireza0/s-ui/cmd/migration"
"github.com/alireza0/s-ui/config"
"github.com/alireza0/s-ui/database/model"
"github.com/alireza0/s-ui/logger"
"github.com/alireza0/s-ui/util/common"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func GetDb(exclude string) ([]byte, error) {
exclude_changes, exclude_stats := false, false
for _, table := range strings.Split(exclude, ",") {
if table == "changes" {
exclude_changes = true
} else if table == "stats" {
exclude_stats = true
}
}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return nil, err
}
dbPath := dir + config.GetName() + "_" + time.Now().Format("20060102-200203") + ".db"
backupDb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
return nil, err
}
defer os.Remove(dbPath)
err = backupDb.AutoMigrate(
&model.Setting{},
&model.Tls{},
&model.Inbound{},
&model.Outbound{},
&model.Endpoint{},
&model.User{},
&model.Stats{},
&model.Client{},
&model.Changes{},
)
if err != nil {
return nil, err
}
var settings []model.Setting
var tls []model.Tls
var inbound []model.Inbound
var outbound []model.Outbound
var endpoint []model.Endpoint
var users []model.User
var clients []model.Client
var stats []model.Stats
var changes []model.Changes
// Perform scans and handle errors
if err := db.Model(&model.Setting{}).Scan(&settings).Error; err != nil {
return nil, err
} else if len(settings) > 0 {
if err := backupDb.Save(settings).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.Tls{}).Scan(&tls).Error; err != nil {
return nil, err
} else if len(tls) > 0 {
if err := backupDb.Save(tls).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.Inbound{}).Scan(&inbound).Error; err != nil {
return nil, err
} else if len(inbound) > 0 {
if err := backupDb.Save(inbound).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.Outbound{}).Scan(&outbound).Error; err != nil {
return nil, err
} else if len(outbound) > 0 {
if err := backupDb.Save(outbound).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.Endpoint{}).Scan(&endpoint).Error; err != nil {
return nil, err
} else if len(endpoint) > 0 {
if err := backupDb.Save(endpoint).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.User{}).Scan(&users).Error; err != nil {
return nil, err
} else if len(users) > 0 {
if err := backupDb.Save(users).Error; err != nil {
return nil, err
}
}
if err := db.Model(&model.Client{}).Scan(&clients).Error; err != nil {
return nil, err
} else if len(clients) > 0 {
if err := backupDb.Save(clients).Error; err != nil {
return nil, err
}
}
if !exclude_stats {
if err := db.Model(&model.Stats{}).Scan(&stats).Error; err != nil {
return nil, err
}
if len(stats) > 0 {
if err := backupDb.Save(stats).Error; err != nil {
return nil, err
}
}
}
if !exclude_changes {
if err := db.Model(&model.Changes{}).Scan(&changes).Error; err != nil {
return nil, err
}
if len(changes) > 0 {
if err := backupDb.Save(changes).Error; err != nil {
return nil, err
}
}
}
// Update WAL
err = backupDb.Exec("PRAGMA wal_checkpoint;").Error
if err != nil {
return nil, err
}
bdb, _ := backupDb.DB()
bdb.Close()
// Open the file for reading
file, err := os.Open(dbPath)
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
}
func ImportDB(file multipart.File) error {
// Check if the file is a SQLite database
isValidDb, err := IsSQLiteDB(file)
if err != nil {
return common.NewErrorf("Error checking db file format: %v", err)
}
if !isValidDb {
return common.NewError("Invalid db file format")
}
// Reset the file reader to the beginning
_, err = file.Seek(0, 0)
if err != nil {
return common.NewErrorf("Error resetting file reader: %v", err)
}
// Save the file as temporary file
tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
// Remove the existing fallback file (if any) before creating one
_, err = os.Stat(tempPath)
if err == nil {
errRemove := os.Remove(tempPath)
if errRemove != nil {
return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
}
}
// Create the temporary file
tempFile, err := os.Create(tempPath)
if err != nil {
return common.NewErrorf("Error creating temporary db file: %v", err)
}
defer tempFile.Close()
// Remove temp file before returning
defer os.Remove(tempPath)
// Close old DB
old_db, _ := db.DB()
old_db.Close()
// Save uploaded file to temporary file
_, err = io.Copy(tempFile, file)
if err != nil {
return common.NewErrorf("Error saving db: %v", err)
}
// Check if we can init db or not
newDb, err := gorm.Open(sqlite.Open(tempPath), &gorm.Config{})
if err != nil {
return common.NewErrorf("Error checking db: %v", err)
}
newDb_db, _ := newDb.DB()
newDb_db.Close()
// Backup the current database for fallback
fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
// Remove the existing fallback file (if any)
_, err = os.Stat(fallbackPath)
if err == nil {
errRemove := os.Remove(fallbackPath)
if errRemove != nil {
return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
}
}
// Move the current database to the fallback location
err = os.Rename(config.GetDBPath(), fallbackPath)
if err != nil {
return common.NewErrorf("Error backing up temporary db file: %v", err)
}
// Remove the temporary file before returning
defer os.Remove(fallbackPath)
// Move temp to DB path
err = os.Rename(tempPath, config.GetDBPath())
if err != nil {
errRename := os.Rename(fallbackPath, config.GetDBPath())
if errRename != nil {
return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
}
return common.NewErrorf("Error moving db file: %v", err)
}
// Migrate DB
migration.MigrateDb()
err = InitDB(config.GetDBPath())
if err != nil {
errRename := os.Rename(fallbackPath, config.GetDBPath())
if errRename != nil {
return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
}
return common.NewErrorf("Error migrating db: %v", err)
}
// Restart app
err = SendSighup()
if err != nil {
return common.NewErrorf("Error restarting app: %v", err)
}
return nil
}
func IsSQLiteDB(file io.Reader) (bool, error) {
signature := []byte("SQLite format 3\x00")
buf := make([]byte, len(signature))
_, err := file.Read(buf)
if err != nil {
return false, err
}
return bytes.Equal(buf, signature), nil
}
func SendSighup() error {
// Get the current process
process, err := os.FindProcess(os.Getpid())
if err != nil {
return err
}
// Send SIGHUP to the current process
go func() {
time.Sleep(3 * time.Second)
if runtime.GOOS == "windows" {
err = process.Kill()
} else {
err = process.Signal(syscall.SIGHUP)
}
if err != nil {
logger.Error("send signal SIGHUP failed:", err)
}
}()
return nil
}
================================================
FILE: database/db.go
================================================
package database
import (
"encoding/json"
"os"
"path"
"strings"
"github.com/alireza0/s-ui/config"
"github.com/alireza0/s-ui/database/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var db *gorm.DB
func initUser() error {
var count int64
err := db.Model(&model.User{}).Count(&count).Error
if err != nil {
return err
}
if count == 0 {
user := &model.User{
Username: "admin",
Password: "admin",
}
return db.Create(user).Error
}
return nil
}
func OpenDB(dbPath string) error {
dir := path.Dir(dbPath)
err := os.MkdirAll(dir, 01740)
if err != nil {
return err
}
var gormLogger logger.Interface
if config.IsDebug() {
gormLogger = logger.Default
} else {
gormLogger = logger.Discard
}
c := &gorm.Config{
Logger: gormLogger,
}
sep := "?"
if strings.Contains(dbPath, "?") {
sep = "&"
}
dsn := dbPath + sep + "_busy_timeout=10000&_journal_mode=WAL"
db, err = gorm.Open(sqlite.Open(dsn), c)
if config.IsDebug() {
db = db.Debug()
}
return err
}
func InitDB(dbPath string) error {
err := OpenDB(dbPath)
if err != nil {
return err
}
// Default Outbounds
if !db.Migrator().HasTable(&model.Outbound{}) {
db.Migrator().CreateTable(&model.Outbound{})
defaultOutbound := []model.Outbound{
{Type: "direct", Tag: "direct", Options: json.RawMessage(`{}`)},
}
db.Create(&defaultOutbound)
}
err = db.AutoMigrate(
&model.Setting{},
&model.Tls{},
&model.Inbound{},
&model.Outbound{},
&model.Service{},
&model.Endpoint{},
&model.User{},
&model.Tokens{},
&model.Stats{},
&model.Client{},
&model.Changes{},
)
if err != nil {
return err
}
err = initUser()
if err != nil {
return err
}
return nil
}
func GetDB() *gorm.DB {
return db
}
func IsNotFound(err error) bool {
return err == gorm.ErrRecordNotFound
}
================================================
FILE: database/model/endpoints.go
================================================
package model
import (
"encoding/json"
)
type Endpoint struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Type string `json:"type" form:"type"`
Tag string `json:"tag" form:"tag" gorm:"unique"`
Options json.RawMessage `json:"-" form:"-"`
Ext json.RawMessage `json:"ext" form:"ext"`
}
func (o *Endpoint) UnmarshalJSON(data []byte) error {
var err error
var raw map[string]interface{}
if err = json.Unmarshal(data, &raw); err != nil {
return err
}
// Extract fixed fields and store the rest in Options
if val, exists := raw["id"].(float64); exists {
o.Id = uint(val)
}
delete(raw, "id")
o.Type, _ = raw["type"].(string)
delete(raw, "type")
o.Tag = raw["tag"].(string)
delete(raw, "tag")
o.Ext, _ = json.MarshalIndent(raw["ext"], "", " ")
delete(raw, "ext")
// Remaining fields
o.Options, err = json.MarshalIndent(raw, "", " ")
return err
}
// MarshalJSON customizes marshalling
func (o Endpoint) MarshalJSON() ([]byte, error) {
// Combine fixed fields and dynamic fields into one map
combined := make(map[string]interface{})
switch o.Type {
case "warp":
combined["type"] = "wireguard"
default:
combined["type"] = o.Type
}
combined["tag"] = o.Tag
if o.Options != nil {
var restFields map[string]json.RawMessage
if err := json.Unmarshal(o.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return json.Marshal(combined)
}
================================================
FILE: database/model/inbounds.go
================================================
package model
import (
"encoding/json"
)
type Inbound struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Type string `json:"type" form:"type"`
Tag string `json:"tag" form:"tag" gorm:"unique"`
// Foreign key to tls table
TlsId uint `json:"tls_id" form:"tls_id"`
Tls *Tls `json:"tls" form:"tls" gorm:"foreignKey:TlsId;references:Id"`
Addrs json.RawMessage `json:"addrs" form:"addrs"`
OutJson json.RawMessage `json:"out_json" form:"out_json"`
Options json.RawMessage `json:"-" form:"-"`
}
func (i *Inbound) UnmarshalJSON(data []byte) error {
var err error
var raw map[string]interface{}
if err = json.Unmarshal(data, &raw); err != nil {
return err
}
// Extract fixed fields and store the rest in Options
if val, exists := raw["id"].(float64); exists {
i.Id = uint(val)
}
delete(raw, "id")
i.Type, _ = raw["type"].(string)
delete(raw, "type")
i.Tag, _ = raw["tag"].(string)
delete(raw, "tag")
// TlsId
if val, exists := raw["tls_id"].(float64); exists {
i.TlsId = uint(val)
}
delete(raw, "tls_id")
delete(raw, "tls")
delete(raw, "users")
// Addrs
i.Addrs, _ = json.MarshalIndent(raw["addrs"], "", " ")
delete(raw, "addrs")
// OutJson
i.OutJson, _ = json.MarshalIndent(raw["out_json"], "", " ")
delete(raw, "out_json")
// Remaining fields
i.Options, err = json.MarshalIndent(raw, "", " ")
return err
}
// MarshalJSON customizes marshalling
func (i Inbound) MarshalJSON() ([]byte, error) {
// Combine fixed fields and dynamic fields into one map
combined := make(map[string]interface{})
combined["type"] = i.Type
combined["tag"] = i.Tag
if i.Tls != nil {
combined["tls"] = i.Tls.Server
}
if i.Options != nil {
var restFields map[string]json.RawMessage
if err := json.Unmarshal(i.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return json.Marshal(combined)
}
func (i Inbound) MarshalFull() (*map[string]interface{}, error) {
combined := make(map[string]interface{})
combined["id"] = i.Id
combined["type"] = i.Type
combined["tag"] = i.Tag
combined["tls_id"] = i.TlsId
combined["addrs"] = i.Addrs
combined["out_json"] = i.OutJson
if i.Options != nil {
var restFields map[string]interface{}
if err := json.Unmarshal(i.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return &combined, nil
}
================================================
FILE: database/model/model.go
================================================
package model
import "encoding/json"
type Setting struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Key string `json:"key" form:"key"`
Value string `json:"value" form:"value"`
}
type Tls struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Name string `json:"name" form:"name"`
Server json.RawMessage `json:"server" form:"server"`
Client json.RawMessage `json:"client" form:"client"`
}
type User struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
LastLogins string `json:"lastLogin"`
}
type Client struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Enable bool `json:"enable" form:"enable"`
Name string `json:"name" form:"name"`
Config json.RawMessage `json:"config,omitempty" form:"config"`
Inbounds json.RawMessage `json:"inbounds" form:"inbounds"`
Links json.RawMessage `json:"links,omitempty" form:"links"`
Volume int64 `json:"volume" form:"volume"`
Expiry int64 `json:"expiry" form:"expiry"`
Down int64 `json:"down" form:"down"`
Up int64 `json:"up" form:"up"`
Desc string `json:"desc" form:"desc"`
Group string `json:"group" form:"group"`
// Delay start and periodic reset
DelayStart bool `json:"delayStart" form:"delayStart" gorm:"default:false;not null"`
AutoReset bool `json:"autoReset" form:"autoReset" gorm:"default:false;not null"`
ResetDays int `json:"resetDays" form:"resetDays" gorm:"default:0;not null"`
NextReset int64 `json:"nextReset" form:"nextReset" gorm:"default:0;not null"`
TotalUp int64 `json:"totalUp" form:"totalUp" gorm:"default:0;not null"`
TotalDown int64 `json:"totalDown" form:"totalDown" gorm:"default:0;not null"`
}
type Stats struct {
Id uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
DateTime int64 `json:"dateTime"`
Resource string `json:"resource"`
Tag string `json:"tag"`
Direction bool `json:"direction"`
Traffic int64 `json:"traffic"`
}
type Changes struct {
Id uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
DateTime int64 `json:"dateTime"`
Actor string `json:"actor"`
Key string `json:"key"`
Action string `json:"action"`
Obj json.RawMessage `json:"obj"`
}
type Tokens struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Desc string `json:"desc" form:"desc"`
Token string `json:"token" form:"token"`
Expiry int64 `json:"expiry" form:"expiry"`
UserId uint `json:"userId" form:"userId"`
User *User `json:"user" gorm:"foreignKey:UserId;references:Id"`
}
================================================
FILE: database/model/outbounds.go
================================================
package model
import "encoding/json"
type Outbound struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Type string `json:"type" form:"type"`
Tag string `json:"tag" form:"tag" gorm:"unique"`
Options json.RawMessage `json:"-" form:"-"`
}
func (o *Outbound) UnmarshalJSON(data []byte) error {
var err error
var raw map[string]interface{}
if err = json.Unmarshal(data, &raw); err != nil {
return err
}
// Extract fixed fields and store the rest in Options
if val, exists := raw["id"].(float64); exists {
o.Id = uint(val)
}
delete(raw, "id")
o.Type, _ = raw["type"].(string)
delete(raw, "type")
o.Tag = raw["tag"].(string)
delete(raw, "tag")
// Remaining fields
o.Options, err = json.MarshalIndent(raw, "", " ")
return err
}
// MarshalJSON customizes marshalling
func (o Outbound) MarshalJSON() ([]byte, error) {
// Combine fixed fields and dynamic fields into one map
combined := make(map[string]interface{})
combined["type"] = o.Type
combined["tag"] = o.Tag
if o.Options != nil {
var restFields map[string]json.RawMessage
if err := json.Unmarshal(o.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return json.Marshal(combined)
}
================================================
FILE: database/model/services.go
================================================
package model
import (
"encoding/json"
)
type Service struct {
Id uint `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Type string `json:"type" form:"type"`
Tag string `json:"tag" form:"tag" gorm:"unique"`
// Foreign key to tls table
TlsId uint `json:"tls_id" form:"tls_id"`
Tls *Tls `json:"tls" form:"tls" gorm:"foreignKey:TlsId;references:Id"`
Options json.RawMessage `json:"-" form:"-"`
}
func (i *Service) UnmarshalJSON(data []byte) error {
var err error
var raw map[string]interface{}
if err = json.Unmarshal(data, &raw); err != nil {
return err
}
// Extract fixed fields and store the rest in Options
if val, exists := raw["id"].(float64); exists {
i.Id = uint(val)
}
delete(raw, "id")
i.Type, _ = raw["type"].(string)
delete(raw, "type")
i.Tag, _ = raw["tag"].(string)
delete(raw, "tag")
// TlsId
if val, exists := raw["tls_id"].(float64); exists {
i.TlsId = uint(val)
}
delete(raw, "tls_id")
delete(raw, "tls")
// Remaining fields
i.Options, err = json.MarshalIndent(raw, "", " ")
return err
}
// MarshalJSON customizes marshalling
func (i Service) MarshalJSON() ([]byte, error) {
// Combine fixed fields and dynamic fields into one map
combined := make(map[string]interface{})
combined["type"] = i.Type
combined["tag"] = i.Tag
if i.Tls != nil {
combined["tls"] = i.Tls.Server
}
if i.Options != nil {
var restFields map[string]json.RawMessage
if err := json.Unmarshal(i.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return json.Marshal(combined)
}
func (i Service) MarshalFull() (*map[string]interface{}, error) {
combined := make(map[string]interface{})
combined["id"] = i.Id
combined["type"] = i.Type
combined["tag"] = i.Tag
combined["tls_id"] = i.TlsId
if i.Options != nil {
var restFields map[string]interface{}
if err := json.Unmarshal(i.Options, &restFields); err != nil {
return nil, err
}
for k, v := range restFields {
combined[k] = v
}
}
return &combined, nil
}
================================================
FILE: docker-build-test.sh
================================================
#!/usr/bin/env bash
# Test Docker multi-platform build (linux/amd64, 386, arm64, arm/v7, arm/v6)
# Requires: frontend_dist/ (run from repo root after building frontend)
set -e
cd "$(dirname "$0")/.."
echo "==> Preparing frontend_dist..."
if [ ! -d "frontend_dist" ] || [ -z "$(ls -A frontend_dist 2>/dev/null)" ]; then
echo "Building frontend..."
(cd frontend && npm install --prefer-offline --no-audit && npm run build)
rm -rf frontend_dist
mkdir -p frontend_dist
cp -R frontend/dist/* frontend_dist/
echo "frontend_dist ready."
else
echo "frontend_dist exists, skipping frontend build."
fi
PLATFORMS="linux/amd64,linux/386,linux/arm64/v8,linux/arm/v7,linux/arm/v6"
echo "==> Testing Docker build for: $PLATFORMS"
docker buildx build \
--platform "$PLATFORMS" \
-f Dockerfile.frontend-artifact \
--build-arg CRONET_RELEASE=latest \
--progress=plain \
. 2>&1 | tee docker-build-test.log
echo "==> Done. Check docker-build-test.log for full output."
================================================
FILE: docker-compose.yml
================================================
---
services:
s-ui:
image: alireza7/s-ui
container_name: s-ui
hostname: "s-ui"
volumes:
- "./db:/app/db"
- "./cert:/app/cert"
tty: true
restart: unless-stopped
ports:
- "2095:2095"
- "2096:2096"
networks:
- s-ui
entrypoint: "./entrypoint.sh"
networks:
s-ui:
driver: bridge
================================================
FILE: entrypoint.sh
================================================
#!/bin/sh
DB_PATH="${SUI_DB_FOLDER:-/app/db}/s-ui.db"
if [ -f "$DB_PATH" ]; then
./sui migrate
fi
exec ./sui
================================================
FILE: go.mod
================================================
module github.com/alireza0/s-ui
go 1.25.7
require (
github.com/gin-contrib/gzip v1.2.5
github.com/gin-contrib/sessions v1.0.4
github.com/gin-gonic/gin v1.12.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/robfig/cron/v3 v3.0.1
github.com/sagernet/sing v0.8.2
github.com/sagernet/sing-box v1.13.2
github.com/shirou/gopsutil/v4 v4.26.2
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/sqlite v1.6.0
gorm.io/gorm v1.31.1
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/anthropics/anthropic-sdk-go v1.26.0 // indirect
github.com/anytls/sing-anytls v0.0.11 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/caddyserver/certmagic v0.25.2 // indirect
github.com/caddyserver/zerossl v0.1.5 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/coder/websocket v1.8.14 // indirect
github.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6 // indirect
github.com/cretz/bine v0.2.0 // indirect
github.com/database64128/netx-go v0.1.1 // indirect
github.com/database64128/tfo-go/v2 v2.3.2 // indirect
github.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa // indirect
github.com/ebitengine/purego v0.10.0 // indirect
github.com/florianl/go-nfqueue/v2 v2.0.2 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gaissmai/bart v0.18.0 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-chi/chi/v5 v5.2.5 // indirect
github.com/go-chi/render v1.0.3 // indirect
github.com/go-json-experiment/json v0.0.0-20250813024750-ebf49471dced // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/gorilla/sessions v1.4.0 // indirect
github.com/hashicorp/yamux v0.1.2 // indirect
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
github.com/insomniacslk/dhcp v0.0.0-20260220084031-5adc3eb26f91 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jsimonetti/rtnetlink v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/keybase/go-keychain v0.0.1 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/libdns/acmedns v0.5.0 // indirect
github.com/libdns/alidns v1.0.6 // indirect
github.com/libdns/cloudflare v0.2.2 // indirect
github.com/libdns/libdns v1.1.1 // indirect
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.30 // indirect
github.com/mdlayher/netlink v1.9.0 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/metacubex/utls v1.8.4 // indirect
github.com/mholt/acmez/v3 v3.1.6 // indirect
github.com/miekg/dns v1.1.72 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/openai/openai-go/v3 v3.24.0 // indirect
github.com/pellet
gitextract_ttjhfz3g/
├── .dockerignore
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── feature_request.md
│ │ └── question-template.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── docker.yml
│ ├── release.yml
│ └── windows.yml
├── .gitignore
├── .gitmodules
├── CONTRIBUTING.md
├── Dockerfile
├── Dockerfile.frontend-artifact
├── LICENSE
├── README.md
├── api/
│ ├── apiHandler.go
│ ├── apiService.go
│ ├── apiV2Handler.go
│ ├── session.go
│ └── utils.go
├── app/
│ └── app.go
├── build.sh
├── cmd/
│ ├── admin.go
│ ├── cmd.go
│ ├── migration/
│ │ ├── 1_1.go
│ │ ├── 1_2.go
│ │ ├── 1_3.go
│ │ └── main.go
│ └── setting.go
├── config/
│ ├── config.go
│ ├── name
│ └── version
├── core/
│ ├── box.go
│ ├── endpoint.go
│ ├── log.go
│ ├── main.go
│ ├── outbound_check.go
│ ├── register.go
│ ├── register_naive.go
│ ├── register_naive_stub.go
│ ├── tracker_conn.go
│ └── tracker_stats.go
├── cronjob/
│ ├── WALCheckpointJob.go
│ ├── checkCoreJob.go
│ ├── cronJob.go
│ ├── delStatsJob.go
│ ├── depleteJob.go
│ └── statsJob.go
├── database/
│ ├── backup.go
│ ├── db.go
│ └── model/
│ ├── endpoints.go
│ ├── inbounds.go
│ ├── model.go
│ ├── outbounds.go
│ └── services.go
├── docker-build-test.sh
├── docker-compose.yml
├── entrypoint.sh
├── go.mod
├── go.sum
├── install.sh
├── logger/
│ └── logger.go
├── main.go
├── middleware/
│ └── domainValidator.go
├── network/
│ ├── auto_https_conn.go
│ └── auto_https_listener.go
├── runSUI.sh
├── s-ui.service
├── s-ui.sh
├── service/
│ ├── client.go
│ ├── config.go
│ ├── endpoints.go
│ ├── inbounds.go
│ ├── outbounds.go
│ ├── panel.go
│ ├── server.go
│ ├── services.go
│ ├── setting.go
│ ├── stats.go
│ ├── tls.go
│ ├── user.go
│ └── warp.go
├── sub/
│ ├── clashService.go
│ ├── jsonService.go
│ ├── linkService.go
│ ├── sub.go
│ ├── subHandler.go
│ └── subService.go
├── util/
│ ├── base64.go
│ ├── common/
│ │ ├── array.go
│ │ ├── err.go
│ │ └── random.go
│ ├── genLink.go
│ ├── linkToJson.go
│ ├── outJson.go
│ ├── subInfo.go
│ └── subToJson.go
├── web/
│ └── web.go
└── windows/
├── README.md
├── build-windows.bat
├── build-windows.ps1
├── install-windows.bat
├── s-ui-windows.bat
├── s-ui-windows.xml
└── uninstall-windows.bat
SYMBOL INDEX (504 symbols across 71 files)
FILE: api/apiHandler.go
type APIHandler (line 11) | type APIHandler struct
method initRouter (line 23) | func (a *APIHandler) initRouter(g *gin.RouterGroup) {
method postHandler (line 34) | func (a *APIHandler) postHandler(c *gin.Context) {
method getHandler (line 66) | func (a *APIHandler) getHandler(c *gin.Context) {
function NewAPIHandler (line 16) | func NewAPIHandler(g *gin.RouterGroup, a2 *APIv2Handler) {
FILE: api/apiService.go
type ApiService (line 16) | type ApiService struct
method LoadData (line 31) | func (a *ApiService) LoadData(c *gin.Context) {
method getData (line 40) | func (a *ApiService) getData(c *gin.Context) (interface{}, error) {
method LoadPartialData (line 114) | func (a *ApiService) LoadPartialData(c *gin.Context, objs []string) er...
method GetUsers (line 175) | func (a *ApiService) GetUsers(c *gin.Context) {
method GetSettings (line 184) | func (a *ApiService) GetSettings(c *gin.Context) {
method GetStats (line 193) | func (a *ApiService) GetStats(c *gin.Context) {
method GetStatus (line 208) | func (a *ApiService) GetStatus(c *gin.Context) {
method GetOnlines (line 214) | func (a *ApiService) GetOnlines(c *gin.Context) {
method GetLogs (line 219) | func (a *ApiService) GetLogs(c *gin.Context) {
method CheckChanges (line 226) | func (a *ApiService) CheckChanges(c *gin.Context) {
method GetKeypairs (line 234) | func (a *ApiService) GetKeypairs(c *gin.Context) {
method GetDb (line 241) | func (a *ApiService) GetDb(c *gin.Context) {
method postActions (line 253) | func (a *ApiService) postActions(c *gin.Context) (string, json.RawMess...
method Login (line 262) | func (a *ApiService) Login(c *gin.Context) {
method ChangePass (line 285) | func (a *ApiService) ChangePass(c *gin.Context) {
method Save (line 300) | func (a *ApiService) Save(c *gin.Context, loginUser string) {
method RestartApp (line 317) | func (a *ApiService) RestartApp(c *gin.Context) {
method RestartSb (line 322) | func (a *ApiService) RestartSb(c *gin.Context) {
method LinkConvert (line 327) | func (a *ApiService) LinkConvert(c *gin.Context) {
method SubConvert (line 333) | func (a *ApiService) SubConvert(c *gin.Context) {
method ImportDb (line 339) | func (a *ApiService) ImportDb(c *gin.Context) {
method Logout (line 350) | func (a *ApiService) Logout(c *gin.Context) {
method LoadTokens (line 359) | func (a *ApiService) LoadTokens() ([]byte, error) {
method GetTokens (line 363) | func (a *ApiService) GetTokens(c *gin.Context) {
method AddToken (line 369) | func (a *ApiService) AddToken(c *gin.Context) {
method DeleteToken (line 382) | func (a *ApiService) DeleteToken(c *gin.Context) {
method GetSingboxConfig (line 388) | func (a *ApiService) GetSingboxConfig(c *gin.Context) {
method GetCheckOutbound (line 400) | func (a *ApiService) GetCheckOutbound(c *gin.Context) {
FILE: api/apiV2Handler.go
type TokenInMemory (line 13) | type TokenInMemory struct
type APIv2Handler (line 19) | type APIv2Handler struct
method initRouter (line 31) | func (a *APIv2Handler) initRouter(g *gin.RouterGroup) {
method postHandler (line 39) | func (a *APIv2Handler) postHandler(c *gin.Context) {
method getHandler (line 61) | func (a *APIv2Handler) getHandler(c *gin.Context) {
method findUsername (line 98) | func (a *APIv2Handler) findUsername(c *gin.Context) string {
method checkToken (line 112) | func (a *APIv2Handler) checkToken(c *gin.Context) {
method ReloadTokens (line 122) | func (a *APIv2Handler) ReloadTokens() {
function NewAPIv2Handler (line 24) | func NewAPIv2Handler(g *gin.RouterGroup) *APIv2Handler {
FILE: api/session.go
constant loginUser (line 13) | loginUser = "LOGIN_USER"
function init (line 16) | func init() {
function SetLoginUser (line 20) | func SetLoginUser(c *gin.Context, userName string, maxAge int) error {
function SetMaxAge (line 36) | func SetMaxAge(c *gin.Context) error {
function GetLoginUser (line 44) | func GetLoginUser(c *gin.Context) string {
function IsLogin (line 57) | func IsLogin(c *gin.Context) bool {
function ClearSession (line 61) | func ClearSession(c *gin.Context) {
FILE: api/utils.go
type Msg (line 13) | type Msg struct
function getRemoteIp (line 19) | func getRemoteIp(c *gin.Context) string {
function getHostname (line 31) | func getHostname(c *gin.Context) string {
function jsonMsg (line 42) | func jsonMsg(c *gin.Context, msg string, err error) {
function jsonObj (line 46) | func jsonObj(c *gin.Context, obj interface{}, err error) {
function jsonMsgObj (line 50) | func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
function pureJsonMsg (line 67) | func pureJsonMsg(c *gin.Context, success bool, msg string) {
function checkLogin (line 81) | func checkLogin(c *gin.Context) {
FILE: app/app.go
type APP (line 18) | type APP struct
method Init (line 32) | func (a *APP) Init() error {
method Start (line 56) | func (a *APP) Start() error {
method Stop (line 90) | func (a *APP) Stop() {
method initLog (line 106) | func (a *APP) initLog() {
method RestartApp (line 121) | func (a *APP) RestartApp() {
method GetCore (line 126) | func (a *APP) GetCore() *core.Core {
function NewApp (line 28) | func NewApp() *APP {
FILE: cmd/admin.go
function resetAdmin (line 11) | func resetAdmin() {
function updateAdmin (line 27) | func updateAdmin(username string, password string) {
function showAdmin (line 45) | func showAdmin() {
FILE: cmd/cmd.go
function ParseCmd (line 13) | func ParseCmd() {
FILE: cmd/migration/1_1.go
function migrateClientSchema (line 13) | func migrateClientSchema(db *gorm.DB) error {
function deleteOldWebSecret (line 66) | func deleteOldWebSecret(db *gorm.DB) error {
function changesObj (line 70) | func changesObj(db *gorm.DB) error {
function to1_1 (line 74) | func to1_1(db *gorm.DB) error {
FILE: cmd/migration/1_2.go
type InboundData (line 14) | type InboundData struct
function moveJsonToDb (line 21) | func moveJsonToDb(db *gorm.DB) error {
function migrateTls (line 231) | func migrateTls(db *gorm.DB) error {
function dropInboundData (line 265) | func dropInboundData(db *gorm.DB) error {
function migrateClients (line 272) | func migrateClients(db *gorm.DB) error {
function migrateChanges (line 295) | func migrateChanges(db *gorm.DB) error {
function to1_2 (line 299) | func to1_2(db *gorm.DB) error {
FILE: cmd/migration/1_3.go
function migrate_dns (line 14) | func migrate_dns(db *gorm.DB) error {
function remove_outbound_strategy (line 98) | func remove_outbound_strategy(db *gorm.DB) error {
function anytls_user_config (line 116) | func anytls_user_config(db *gorm.DB) error {
function to1_3 (line 141) | func to1_3(db *gorm.DB) error {
FILE: cmd/migration/main.go
function MigrateDb (line 14) | func MigrateDb() {
FILE: cmd/setting.go
function resetSetting (line 18) | func resetSetting() {
function updateSetting (line 34) | func updateSetting(port int, path string, subPort int, subPath string) {
function showSetting (line 77) | func showSetting() {
function getPublicIP (line 115) | func getPublicIP() string {
function getPanelURI (line 163) | func getPanelURI() {
FILE: config/config.go
type LogLevel (line 18) | type LogLevel
constant Debug (line 21) | Debug LogLevel = "debug"
constant Info (line 22) | Info LogLevel = "info"
constant Warn (line 23) | Warn LogLevel = "warn"
constant Error (line 24) | Error LogLevel = "error"
function GetVersion (line 27) | func GetVersion() string {
function GetName (line 31) | func GetName() string {
function GetLogLevel (line 35) | func GetLogLevel() LogLevel {
function IsDebug (line 46) | func IsDebug() bool {
function GetDBFolderPath (line 50) | func GetDBFolderPath() string {
function GetDBPath (line 66) | func GetDBPath() string {
FILE: core/box.go
type Box (line 38) | type Box struct
method PreStart (line 402) | func (s *Box) PreStart() error {
method Start (line 420) | func (s *Box) Start() error {
method preStart (line 429) | func (s *Box) preStart() error {
method start (line 452) | func (s *Box) start() error {
method Close (line 484) | func (s *Box) Close() error {
method Uptime (line 560) | func (s *Box) Uptime() uint32 {
method Network (line 564) | func (s *Box) Network() adapter.NetworkManager {
method Router (line 568) | func (s *Box) Router() adapter.Router {
method Inbound (line 572) | func (s *Box) Inbound() adapter.InboundManager {
method Outbound (line 576) | func (s *Box) Outbound() adapter.OutboundManager {
method Endpoint (line 580) | func (s *Box) Endpoint() adapter.EndpointManager {
method StatsTracker (line 584) | func (s *Box) StatsTracker() *StatsTracker {
method ConnTracker (line 588) | func (s *Box) ConnTracker() *ConnTracker {
type Options (line 57) | type Options struct
function Context (line 62) | func Context(
function NewBox (line 96) | func NewBox(options Options) (*Box, error) {
FILE: core/endpoint.go
method AddInbound (line 11) | func (c *Core) AddInbound(config []byte) error {
method RemoveInbound (line 36) | func (c *Core) RemoveInbound(tag string) error {
method AddOutbound (line 44) | func (c *Core) AddOutbound(config []byte) error {
method RemoveOutbound (line 74) | func (c *Core) RemoveOutbound(tag string) error {
method AddEndpoint (line 82) | func (c *Core) AddEndpoint(config []byte) error {
method RemoveEndpoint (line 108) | func (c *Core) RemoveEndpoint(tag string) error {
method AddService (line 116) | func (c *Core) AddService(config []byte) error {
method RemoveService (line 141) | func (c *Core) RemoveService(tag string) error {
FILE: core/log.go
type PlatformWriter (line 18) | type PlatformWriter struct
method DisableColors (line 20) | func (p PlatformWriter) DisableColors() bool {
method WriteMessage (line 23) | func (p PlatformWriter) WriteMessage(level log.Level, message string) {
function NewFactory (line 38) | func NewFactory(options log.Options) (log.Factory, error) {
type defaultFactory (line 88) | type defaultFactory struct
method Start (line 116) | func (f *defaultFactory) Start() error {
method Close (line 128) | func (f *defaultFactory) Close() error {
method Level (line 135) | func (f *defaultFactory) Level() log.Level {
method SetLevel (line 139) | func (f *defaultFactory) SetLevel(level log.Level) {
method Logger (line 143) | func (f *defaultFactory) Logger() log.ContextLogger {
method NewLogger (line 147) | func (f *defaultFactory) NewLogger(tag string) log.ContextLogger {
method Subscribe (line 151) | func (f *defaultFactory) Subscribe() (subscription observable.Subscrip...
method UnSubscribe (line 155) | func (f *defaultFactory) UnSubscribe(sub observable.Subscription[log.E...
function NewDefaultFactory (line 99) | func NewDefaultFactory(
type observableLogger (line 159) | type observableLogger struct
method Log (line 164) | func (l *observableLogger) Log(ctx context.Context, level log.Level, a...
method Trace (line 188) | func (l *observableLogger) Trace(args ...any) {
method Debug (line 192) | func (l *observableLogger) Debug(args ...any) {
method Info (line 196) | func (l *observableLogger) Info(args ...any) {
method Warn (line 200) | func (l *observableLogger) Warn(args ...any) {
method Error (line 204) | func (l *observableLogger) Error(args ...any) {
method Fatal (line 208) | func (l *observableLogger) Fatal(args ...any) {
method Panic (line 212) | func (l *observableLogger) Panic(args ...any) {
method TraceContext (line 216) | func (l *observableLogger) TraceContext(ctx context.Context, args ...a...
method DebugContext (line 220) | func (l *observableLogger) DebugContext(ctx context.Context, args ...a...
method InfoContext (line 224) | func (l *observableLogger) InfoContext(ctx context.Context, args ...an...
method WarnContext (line 228) | func (l *observableLogger) WarnContext(ctx context.Context, args ...an...
method ErrorContext (line 232) | func (l *observableLogger) ErrorContext(ctx context.Context, args ...a...
method FatalContext (line 236) | func (l *observableLogger) FatalContext(ctx context.Context, args ...a...
method PanicContext (line 240) | func (l *observableLogger) PanicContext(ctx context.Context, args ...a...
FILE: core/main.go
type Core (line 30) | type Core struct
method GetCtx (line 44) | func (c *Core) GetCtx() context.Context {
method GetInstance (line 48) | func (c *Core) GetInstance() *Box {
method Start (line 52) | func (c *Core) Start(sbConfig []byte) error {
method Stop (line 85) | func (c *Core) Stop() error {
method IsRunning (line 95) | func (c *Core) IsRunning() bool {
function NewCore (line 35) | func NewCore() *Core {
FILE: core/outbound_check.go
constant checkTimeout (line 10) | checkTimeout = 15 * time.Second
type CheckOutboundResult (line 12) | type CheckOutboundResult struct
function CheckOutbound (line 18) | func CheckOutbound(ctx context.Context, tag string, link string) (result...
FILE: core/register.go
function InboundRegistry (line 46) | func InboundRegistry() *inbound.Registry {
function OutboundRegistry (line 73) | func OutboundRegistry() *outbound.Registry {
function EndpointRegistry (line 102) | func EndpointRegistry() *endpoint.Registry {
function DNSTransportRegistry (line 111) | func DNSTransportRegistry() *dns.TransportRegistry {
function ServiceRegistry (line 130) | func ServiceRegistry() *service.Registry {
FILE: core/register_naive.go
function registerNaiveOutbound (line 10) | func registerNaiveOutbound(registry *outbound.Registry) {
FILE: core/register_naive_stub.go
function registerNaiveOutbound (line 10) | func registerNaiveOutbound(registry *outbound.Registry) {
FILE: core/tracker_conn.go
type ConnectionInfo (line 13) | type ConnectionInfo struct
type ConnTracker (line 21) | type ConnTracker struct
method generateConnectionID (line 32) | func (c *ConnTracker) generateConnectionID() string {
method RoutedConnection (line 36) | func (c *ConnTracker) RoutedConnection(ctx context.Context, conn net.C...
method RoutedPacketConnection (line 50) | func (c *ConnTracker) RoutedPacketConnection(ctx context.Context, conn...
method CloseConnByInbound (line 64) | func (c *ConnTracker) CloseConnByInbound(inbound string) int {
method trackConnection (line 84) | func (c *ConnTracker) trackConnection(connID string, connInfo *Connect...
method untrackConnection (line 90) | func (c *ConnTracker) untrackConnection(connID string) {
method createWrappedConn (line 96) | func (c *ConnTracker) createWrappedConn(conn net.Conn, connID string) ...
method createWrappedPacketConn (line 103) | func (c *ConnTracker) createWrappedPacketConn(conn network.PacketConn,...
function NewConnTracker (line 26) | func NewConnTracker() *ConnTracker {
type wrappedConn (line 110) | type wrappedConn struct
method Close (line 115) | func (w *wrappedConn) Close() error {
method Upstream (line 120) | func (w *wrappedConn) Upstream() any {
type wrappedPacketConn (line 124) | type wrappedPacketConn struct
method Close (line 129) | func (w *wrappedPacketConn) Close() error {
method Upstream (line 134) | func (w *wrappedPacketConn) Upstream() any {
FILE: core/tracker_stats.go
type Counter (line 17) | type Counter struct
type StatsTracker (line 22) | type StatsTracker struct
method getReadCounters (line 37) | func (c *StatsTracker) getReadCounters(inbound string, outbound string...
method loadOrCreateCounter (line 58) | func (c *StatsTracker) loadOrCreateCounter(obj *map[string]Counter, na...
method RoutedConnection (line 68) | func (c *StatsTracker) RoutedConnection(ctx context.Context, conn net....
method RoutedPacketConnection (line 73) | func (c *StatsTracker) RoutedPacketConnection(ctx context.Context, con...
method GetStats (line 78) | func (c *StatsTracker) GetStats() *[]model.Stats {
function NewStatsTracker (line 29) | func NewStatsTracker() *StatsTracker {
FILE: cronjob/WALCheckpointJob.go
type WALCheckpointJob (line 8) | type WALCheckpointJob struct
method Run (line 14) | func (s *WALCheckpointJob) Run() {
function NewWALCheckpointJob (line 10) | func NewWALCheckpointJob() *WALCheckpointJob {
FILE: cronjob/checkCoreJob.go
type CheckCoreJob (line 7) | type CheckCoreJob struct
method Run (line 15) | func (s *CheckCoreJob) Run() {
function NewCheckCoreJob (line 11) | func NewCheckCoreJob() *CheckCoreJob {
FILE: cronjob/cronJob.go
type CronJob (line 9) | type CronJob struct
method Start (line 17) | func (c *CronJob) Start(loc *time.Location, trafficAge int) error {
method Stop (line 39) | func (c *CronJob) Stop() {
function NewCronJob (line 13) | func NewCronJob() *CronJob {
FILE: cronjob/delStatsJob.go
type DelStatsJob (line 8) | type DelStatsJob struct
method Run (line 19) | func (s *DelStatsJob) Run() {
function NewDelStatsJob (line 13) | func NewDelStatsJob(ta int) *DelStatsJob {
FILE: cronjob/depleteJob.go
type DepleteJob (line 9) | type DepleteJob struct
method Run (line 18) | func (s *DepleteJob) Run() {
function NewDepleteJob (line 14) | func NewDepleteJob() *DepleteJob {
FILE: cronjob/statsJob.go
type StatsJob (line 8) | type StatsJob struct
method Run (line 19) | func (s *StatsJob) Run() {
function NewStatsJob (line 13) | func NewStatsJob(saveTraffic bool) *StatsJob {
FILE: database/backup.go
function GetDb (line 25) | func GetDb(exclude string) ([]byte, error) {
function ImportDB (line 169) | func ImportDB(file multipart.File) error {
function IsSQLiteDB (line 272) | func IsSQLiteDB(file io.Reader) (bool, error) {
function SendSighup (line 282) | func SendSighup() error {
FILE: database/db.go
function initUser (line 19) | func initUser() error {
function OpenDB (line 35) | func OpenDB(dbPath string) error {
function InitDB (line 66) | func InitDB(dbPath string) error {
function GetDB (line 105) | func GetDB() *gorm.DB {
function IsNotFound (line 109) | func IsNotFound(err error) bool {
FILE: database/model/endpoints.go
type Endpoint (line 7) | type Endpoint struct
method UnmarshalJSON (line 15) | func (o *Endpoint) UnmarshalJSON(data []byte) error {
method MarshalJSON (line 40) | func (o Endpoint) MarshalJSON() ([]byte, error) {
FILE: database/model/inbounds.go
type Inbound (line 7) | type Inbound struct
method UnmarshalJSON (line 21) | func (i *Inbound) UnmarshalJSON(data []byte) error {
method MarshalJSON (line 60) | func (i Inbound) MarshalJSON() ([]byte, error) {
method MarshalFull (line 83) | func (i Inbound) MarshalFull() (*map[string]interface{}, error) {
FILE: database/model/model.go
type Setting (line 5) | type Setting struct
type Tls (line 11) | type Tls struct
type User (line 18) | type User struct
type Client (line 25) | type Client struct
type Stats (line 48) | type Stats struct
type Changes (line 57) | type Changes struct
type Tokens (line 66) | type Tokens struct
FILE: database/model/outbounds.go
type Outbound (line 5) | type Outbound struct
method UnmarshalJSON (line 12) | func (o *Outbound) UnmarshalJSON(data []byte) error {
method MarshalJSON (line 35) | func (o Outbound) MarshalJSON() ([]byte, error) {
FILE: database/model/services.go
type Service (line 7) | type Service struct
method UnmarshalJSON (line 19) | func (i *Service) UnmarshalJSON(data []byte) error {
method MarshalJSON (line 49) | func (i Service) MarshalJSON() ([]byte, error) {
method MarshalFull (line 72) | func (i Service) MarshalFull() (*map[string]interface{}, error) {
FILE: logger/logger.go
function InitLogger (line 20) | func InitLogger(level logging.Level) {
function GetLogger (line 56) | func GetLogger() *logging.Logger {
function Debug (line 60) | func Debug(args ...interface{}) {
function Debugf (line 65) | func Debugf(format string, args ...interface{}) {
function Info (line 70) | func Info(args ...interface{}) {
function Infof (line 75) | func Infof(format string, args ...interface{}) {
function Warning (line 80) | func Warning(args ...interface{}) {
function Warningf (line 85) | func Warningf(format string, args ...interface{}) {
function Error (line 90) | func Error(args ...interface{}) {
function Errorf (line 95) | func Errorf(format string, args ...interface{}) {
function addToBuffer (line 100) | func addToBuffer(level string, newLog string) {
function GetLogs (line 118) | func GetLogs(c int, level string) []string {
FILE: main.go
function runApp (line 13) | func runApp() {
function main (line 42) | func main() {
FILE: middleware/domainValidator.go
function DomainValidator (line 11) | func DomainValidator(domain string) gin.HandlerFunc {
FILE: network/auto_https_conn.go
type AutoHttpsConn (line 12) | type AutoHttpsConn struct
method readRequest (line 27) | func (c *AutoHttpsConn) readRequest() bool {
method Read (line 52) | func (c *AutoHttpsConn) Read(buf []byte) (int, error) {
function NewAutoHttpsConn (line 21) | func NewAutoHttpsConn(conn net.Conn) net.Conn {
FILE: network/auto_https_listener.go
type AutoHttpsListener (line 5) | type AutoHttpsListener struct
method Accept (line 15) | func (l *AutoHttpsListener) Accept() (net.Conn, error) {
function NewAutoHttpsListener (line 9) | func NewAutoHttpsListener(listener net.Listener) net.Listener {
FILE: service/client.go
type ClientService (line 18) | type ClientService struct
method Get (line 20) | func (s *ClientService) Get(id string) (*[]model.Client, error) {
method getById (line 27) | func (s *ClientService) getById(id string) (*[]model.Client, error) {
method GetAll (line 38) | func (s *ClientService) GetAll() (*[]model.Client, error) {
method Save (line 50) | func (s *ClientService) Save(tx *gorm.DB, act string, data json.RawMes...
method updateLinksWithFixedInbounds (line 173) | func (s *ClientService) updateLinksWithFixedInbounds(tx *gorm.DB, clie...
method UpdateClientsOnInboundAdd (line 224) | func (s *ClientService) UpdateClientsOnInboundAdd(tx *gorm.DB, initIds...
method UpdateClientsOnInboundDelete (line 274) | func (s *ClientService) UpdateClientsOnInboundDelete(tx *gorm.DB, id u...
method UpdateLinksByInboundChange (line 321) | func (s *ClientService) UpdateLinksByInboundChange(tx *gorm.DB, inboun...
method DepleteClients (line 367) | func (s *ClientService) DepleteClients() ([]uint, error) {
method ResetClients (line 434) | func (s *ClientService) ResetClients(tx *gorm.DB, dt int64) ([]uint, e...
method findInboundsChanges (line 517) | func (s *ClientService) findInboundsChanges(tx *gorm.DB, client *model...
FILE: service/config.go
type ConfigService (line 25) | type ConfigService struct
method GetConfig (line 52) | func (s *ConfigService) GetConfig(data string) (*[]byte, error) {
method StartCore (line 89) | func (s *ConfigService) StartCore() error {
method RestartCore (line 128) | func (s *ConfigService) RestartCore() error {
method restartCoreWithConfig (line 136) | func (s *ConfigService) restartCoreWithConfig(config json.RawMessage) ...
method StopCore (line 169) | func (s *ConfigService) StopCore() error {
method CheckOutbound (line 178) | func (s *ConfigService) CheckOutbound(tag string, link string) core.Ch...
method Save (line 188) | func (s *ConfigService) Save(obj string, act string, data json.RawMess...
method CheckChanges (line 263) | func (s *ConfigService) CheckChanges(lu string) (bool, error) {
method GetChanges (line 281) | func (s *ConfigService) GetChanges(actor string, chngKey string, count...
type SingBoxConfig (line 35) | type SingBoxConfig struct
function NewConfigService (line 47) | func NewConfigService(core *core.Core) *ConfigService {
FILE: service/endpoints.go
type EndpointService (line 14) | type EndpointService struct
method GetAll (line 18) | func (o *EndpointService) GetAll() (*[]map[string]interface{}, error) {
method GetAllConfig (line 47) | func (o *EndpointService) GetAllConfig(db *gorm.DB) ([]json.RawMessage...
method Save (line 64) | func (s *EndpointService) Save(tx *gorm.DB, act string, data json.RawM...
FILE: service/inbounds.go
type InboundService (line 17) | type InboundService struct
method Get (line 21) | func (s *InboundService) Get(ids string) (*[]map[string]interface{}, e...
method getById (line 28) | func (s *InboundService) getById(ids string) (*[]map[string]interface{...
method GetAll (line 46) | func (s *InboundService) GetAll() (*[]map[string]interface{}, error) {
method FromIds (line 93) | func (s *InboundService) FromIds(ids []uint) ([]*model.Inbound, error) {
method Save (line 103) | func (s *InboundService) Save(tx *gorm.DB, act string, data json.RawMe...
method UpdateOutJsons (line 204) | func (s *InboundService) UpdateOutJsons(tx *gorm.DB, inboundIds []uint...
method GetAllConfig (line 224) | func (s *InboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage,...
method hasUser (line 245) | func (s *InboundService) hasUser(inboundType string) bool {
method fetchUsers (line 253) | func (s *InboundService) fetchUsers(db *gorm.DB, inboundType string, c...
method addUsers (line 286) | func (s *InboundService) addUsers(db *gorm.DB, inboundJson []byte, inb...
method initUsers (line 306) | func (s *InboundService) initUsers(db *gorm.DB, inboundJson []byte, cl...
method RestartInbounds (line 331) | func (s *InboundService) RestartInbounds(tx *gorm.DB, ids []uint) error {
FILE: service/outbounds.go
type OutboundService (line 14) | type OutboundService struct
method GetAll (line 16) | func (o *OutboundService) GetAll() (*[]map[string]interface{}, error) {
method GetAllConfig (line 44) | func (o *OutboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage...
method Save (line 61) | func (s *OutboundService) Save(tx *gorm.DB, act string, data json.RawM...
FILE: service/panel.go
type PanelService (line 12) | type PanelService struct
method RestartPanel (line 15) | func (s *PanelService) RestartPanel(delay time.Duration) error {
FILE: service/server.go
type ServerService (line 25) | type ServerService struct
method GetStatus (line 27) | func (s *ServerService) GetStatus(request string) *map[string]interfac...
method GetCpuPercent (line 55) | func (s *ServerService) GetCpuPercent() float64 {
method GetMemInfo (line 65) | func (s *ServerService) GetMemInfo() map[string]interface{} {
method GetDiskInfo (line 77) | func (s *ServerService) GetDiskInfo() map[string]interface{} {
method GetDiskIO (line 89) | func (s *ServerService) GetDiskIO() map[string]interface{} {
method GetSwapInfo (line 108) | func (s *ServerService) GetSwapInfo() map[string]interface{} {
method GetNetInfo (line 120) | func (s *ServerService) GetNetInfo() map[string]interface{} {
method GetSingboxInfo (line 137) | func (s *ServerService) GetSingboxInfo() map[string]interface{} {
method GetSystemInfo (line 155) | func (s *ServerService) GetSystemInfo() map[string]interface{} {
method GetLogs (line 193) | func (s *ServerService) GetLogs(count string, level string) []string {
method GenKeypair (line 201) | func (s *ServerService) GenKeypair(keyType string, options string) []s...
method generateECHKeyPair (line 220) | func (s *ServerService) generateECHKeyPair(serverName string) []string {
method generateTLSKeyPair (line 228) | func (s *ServerService) generateTLSKeyPair(serverName string) []string {
method generateRealityKeyPair (line 236) | func (s *ServerService) generateRealityKeyPair() []string {
method generateWireGuardKey (line 245) | func (s *ServerService) generateWireGuardKey(pk string) []string {
method GetDatabaseInfo (line 257) | func (s *ServerService) GetDatabaseInfo() map[string]int64 {
FILE: service/services.go
type ServicesService (line 14) | type ServicesService struct
method GetAll (line 16) | func (s *ServicesService) GetAll() (*[]map[string]interface{}, error) {
method GetAllConfig (line 46) | func (s *ServicesService) GetAllConfig(db *gorm.DB) ([]json.RawMessage...
method Save (line 63) | func (s *ServicesService) Save(tx *gorm.DB, act string, data json.RawM...
method RestartServices (line 129) | func (s *ServicesService) RestartServices(tx *gorm.DB, ids []uint) err...
FILE: service/setting.go
type SettingService (line 72) | type SettingService struct
method GetAllSetting (line 75) | func (s *SettingService) GetAllSetting() (*map[string]string, error) {
method ResetSettings (line 106) | func (s *SettingService) ResetSettings() error {
method getSetting (line 111) | func (s *SettingService) getSetting(key string) (*model.Setting, error) {
method getString (line 121) | func (s *SettingService) getString(key string) (string, error) {
method saveSetting (line 135) | func (s *SettingService) saveSetting(key string, value string) error {
method setString (line 151) | func (s *SettingService) setString(key string, value string) error {
method getBool (line 155) | func (s *SettingService) getBool(key string) (bool, error) {
method getInt (line 167) | func (s *SettingService) getInt(key string) (int, error) {
method setInt (line 175) | func (s *SettingService) setInt(key string, value int) error {
method GetListen (line 178) | func (s *SettingService) GetListen() (string, error) {
method GetWebDomain (line 182) | func (s *SettingService) GetWebDomain() (string, error) {
method GetPort (line 186) | func (s *SettingService) GetPort() (int, error) {
method SetPort (line 190) | func (s *SettingService) SetPort(port int) error {
method GetCertFile (line 194) | func (s *SettingService) GetCertFile() (string, error) {
method GetKeyFile (line 198) | func (s *SettingService) GetKeyFile() (string, error) {
method GetWebPath (line 202) | func (s *SettingService) GetWebPath() (string, error) {
method SetWebPath (line 216) | func (s *SettingService) SetWebPath(webPath string) error {
method GetSecret (line 226) | func (s *SettingService) GetSecret() ([]byte, error) {
method GetSessionMaxAge (line 237) | func (s *SettingService) GetSessionMaxAge() (int, error) {
method GetTrafficAge (line 241) | func (s *SettingService) GetTrafficAge() (int, error) {
method GetTimeLocation (line 245) | func (s *SettingService) GetTimeLocation() (*time.Location, error) {
method GetSubListen (line 262) | func (s *SettingService) GetSubListen() (string, error) {
method GetSubPort (line 266) | func (s *SettingService) GetSubPort() (int, error) {
method SetSubPort (line 270) | func (s *SettingService) SetSubPort(subPort int) error {
method GetSubPath (line 274) | func (s *SettingService) GetSubPath() (string, error) {
method SetSubPath (line 288) | func (s *SettingService) SetSubPath(subPath string) error {
method GetSubDomain (line 298) | func (s *SettingService) GetSubDomain() (string, error) {
method GetSubCertFile (line 302) | func (s *SettingService) GetSubCertFile() (string, error) {
method GetSubKeyFile (line 306) | func (s *SettingService) GetSubKeyFile() (string, error) {
method GetSubUpdates (line 310) | func (s *SettingService) GetSubUpdates() (int, error) {
method GetSubEncode (line 314) | func (s *SettingService) GetSubEncode() (bool, error) {
method GetSubShowInfo (line 318) | func (s *SettingService) GetSubShowInfo() (bool, error) {
method GetSubURI (line 322) | func (s *SettingService) GetSubURI() (string, error) {
method GetFinalSubURI (line 326) | func (s *SettingService) GetFinalSubURI(host string) (string, error) {
method GetConfig (line 349) | func (s *SettingService) GetConfig() (string, error) {
method SetConfig (line 353) | func (s *SettingService) SetConfig(config string) error {
method SaveConfig (line 357) | func (s *SettingService) SaveConfig(tx *gorm.DB, config json.RawMessag...
method Save (line 365) | func (s *SettingService) Save(tx *gorm.DB, data json.RawMessage) error {
method GetSubJsonExt (line 410) | func (s *SettingService) GetSubJsonExt() (string, error) {
method GetSubClashExt (line 414) | func (s *SettingService) GetSubClashExt() (string, error) {
method fileExists (line 418) | func (s *SettingService) fileExists(path string) error {
FILE: service/stats.go
type onlines (line 13) | type onlines struct
type StatsService (line 21) | type StatsService struct
method SaveStats (line 24) | func (s *StatsService) SaveStats(enableTraffic bool) error {
method GetStats (line 81) | func (s *StatsService) GetStats(resource string, tag string, limit int...
method downsampleStats (line 104) | func (s *StatsService) downsampleStats(stats []model.Stats, maxRows in...
method GetOnlines (line 147) | func (s *StatsService) GetOnlines() (onlines, error) {
method DelOldStats (line 150) | func (s *StatsService) DelOldStats(days int) error {
FILE: service/tls.go
type TlsService (line 13) | type TlsService struct
method GetAll (line 18) | func (s *TlsService) GetAll() ([]model.Tls, error) {
method Save (line 29) | func (s *TlsService) Save(tx *gorm.DB, action string, data json.RawMes...
FILE: service/user.go
type UserService (line 13) | type UserService struct
method GetFirstUser (line 16) | func (s *UserService) GetFirstUser() (*model.User, error) {
method UpdateFirstUser (line 29) | func (s *UserService) UpdateFirstUser(username string, password string...
method Login (line 50) | func (s *UserService) Login(username string, password string, remoteIP...
method CheckUser (line 58) | func (s *UserService) CheckUser(username string, password string, remo...
method GetUsers (line 83) | func (s *UserService) GetUsers() (*[]model.User, error) {
method ChangePass (line 93) | func (s *UserService) ChangePass(id string, oldPass string, newUser st...
method LoadTokens (line 105) | func (s *UserService) LoadTokens() ([]byte, error) {
method GetUserTokens (line 124) | func (s *UserService) GetUserTokens(username string) (*[]model.Tokens,...
method AddToken (line 135) | func (s *UserService) AddToken(username string, expiry int64, desc str...
method DeleteToken (line 158) | func (s *UserService) DeleteToken(id string) error {
FILE: service/warp.go
type WarpService (line 21) | type WarpService struct
method getWarpInfo (line 23) | func (s *WarpService) getWarpInfo(deviceId string, accessToken string)...
method RegisterWarp (line 48) | func (s *WarpService) RegisterWarp(ep *model.Endpoint) error {
method getReserved (line 154) | func (s *WarpService) getReserved(clientID string) []int {
method SetWarpLicense (line 179) | func (s *WarpService) SetWarpLicense(old_license string, ep *model.End...
FILE: sub/clashService.go
type ClashService (line 13) | type ClashService struct
method GetClash (line 64) | func (s *ClashService) GetClash(subId string) (*string, []string, erro...
method getClashConfig (line 106) | func (s *ClashService) getClashConfig() (string, error) {
method ConvertToClashMeta (line 115) | func (s *ClashService) ConvertToClashMeta(outbounds *[]map[string]inte...
constant basicClashConfig (line 19) | basicClashConfig = `mixed-port: 7890
constant ProxyGroups (line 53) | ProxyGroups = `- name: Proxy
FILE: sub/jsonService.go
constant defaultJson (line 14) | defaultJson = `
type JsonService (line 46) | type JsonService struct
method GetJson (line 51) | func (j *JsonService) GetJson(subId string, format string) (*string, [...
method getData (line 98) | func (j *JsonService) getData(subId string) (*model.Client, []*model.I...
method getOutbounds (line 118) | func (j *JsonService) getOutbounds(clientConfig json.RawMessage, inbou...
method addDefaultOutbounds (line 224) | func (j *JsonService) addDefaultOutbounds(outbounds *[]map[string]inte...
method addOthers (line 247) | func (j *JsonService) addOthers(jsonConfig *map[string]interface{}) er...
method pushMixed (line 311) | func (j *JsonService) pushMixed(outbounds *[]map[string]interface{}, o...
FILE: sub/linkService.go
type Link (line 11) | type Link struct
type LinkService (line 17) | type LinkService struct
method GetLinks (line 20) | func (s *LinkService) GetLinks(linkJson *json.RawMessage, types string...
method addClientInfo (line 43) | func (s *LinkService) addClientInfo(uri string, clientInfo string) str...
FILE: sub/sub.go
type Server (line 20) | type Server struct
method initRouter (line 37) | func (s *Server) initRouter() (*gin.Engine, error) {
method Start (line 68) | func (s *Server) Start() (err error) {
method Stop (line 135) | func (s *Server) Stop() error {
method GetCtx (line 153) | func (s *Server) GetCtx() context.Context {
function NewServer (line 29) | func NewServer() *Server {
FILE: sub/subHandler.go
type SubHandler (line 10) | type SubHandler struct
method initRouter (line 22) | func (s *SubHandler) initRouter(g *gin.RouterGroup) {
method subs (line 27) | func (s *SubHandler) subs(c *gin.Context) {
method subHeaders (line 59) | func (s *SubHandler) subHeaders(c *gin.Context) {
method addHeaders (line 74) | func (s *SubHandler) addHeaders(c *gin.Context, headers []string) {
function NewSubHandler (line 17) | func NewSubHandler(g *gin.RouterGroup) {
FILE: sub/subService.go
type SubService (line 15) | type SubService struct
method GetSubs (line 20) | func (s *SubService) GetSubs(subId string) (*string, []string, error) {
method getClientBySubId (line 47) | func (j *SubService) getClientBySubId(subId string) (*model.Client, er...
method getClientHeaders (line 57) | func (s *SubService) getClientHeaders(client *model.Client) []string {
method getClientInfo (line 62) | func (s *SubService) getClientInfo(c *model.Client) string {
method formatTraffic (line 79) | func (s *SubService) formatTraffic(trafficBytes int64) string {
FILE: util/base64.go
function StrOrBase64Encoded (line 6) | func StrOrBase64Encoded(str string) string {
function B64StrToByte (line 14) | func B64StrToByte(str string) ([]byte, error) {
function ByteToB64Str (line 18) | func ByteToB64Str(b []byte) string {
FILE: util/common/array.go
function UnionUintArray (line 4) | func UnionUintArray(a []uint, b []uint) []uint {
function DiffUintArray (line 21) | func DiffUintArray(a []uint, b []uint) []uint {
FILE: util/common/err.go
function NewErrorf (line 10) | func NewErrorf(format string, a ...interface{}) error {
function NewError (line 15) | func NewError(a ...interface{}) error {
function Recover (line 20) | func Recover(msg string) interface{} {
FILE: util/common/random.go
function Random (line 22) | func Random(n int) string {
function RandomInt (line 42) | func RandomInt(n int) int {
FILE: util/genLink.go
type LinkParam (line 16) | type LinkParam struct
function LinkGenerator (line 21) | func LinkGenerator(clientConfig json.RawMessage, i *model.Inbound, hostn...
function prepareTls (line 104) | func prepareTls(t *model.Tls) map[string]interface{} {
function socksLink (line 130) | func socksLink(userConfig map[string]interface{}, addrs []map[string]int...
function httpLink (line 138) | func httpLink(userConfig map[string]interface{}, addrs []map[string]inte...
function shadowsocksLink (line 150) | func shadowsocksLink(
function naiveLink (line 179) | func naiveLink(
function hysteriaLink (line 221) | func hysteriaLink(
function hysteria2Link (line 271) | func hysteria2Link(
function anytlsLink (line 324) | func anytlsLink(
function tuicLink (line 346) | func tuicLink(
function vlessLink (line 373) | func vlessLink(
function trojanLink (line 400) | func trojanLink(
function vmessLink (line 423) | func vmessLink(
function populateVmessTlsParams (line 488) | func populateVmessTlsParams(obj map[string]interface{}, tlsConfig interf...
function toBase64 (line 512) | func toBase64(d []byte) string {
function addParams (line 516) | func addParams(uri string, params []LinkParam, remark string) string {
function getTransportParams (line 532) | func getTransportParams(t interface{}) []LinkParam {
function getTlsParams (line 582) | func getTlsParams(params *[]LinkParam, tls map[string]interface{}, insec...
FILE: util/linkToJson.go
function GetOutbound (line 14) | func GetOutbound(uri string, i int) (*map[string]interface{}, string, er...
function vmess (line 41) | func vmess(data string, i int) (*map[string]interface{}, string, error) {
function vless (line 138) | func vless(u *url.URL, i int) (*map[string]interface{}, string, error) {
function trojan (line 168) | func trojan(u *url.URL, i int) (*map[string]interface{}, string, error) {
function hy (line 197) | func hy(u *url.URL, i int) (*map[string]interface{}, string, error) {
function hy2 (line 242) | func hy2(u *url.URL, i int) (*map[string]interface{}, string, error) {
function anytls (line 293) | func anytls(u *url.URL, i int) (*map[string]interface{}, string, error) {
function tuic (line 321) | func tuic(u *url.URL, i int) (*map[string]interface{}, string, error) {
function ss (line 353) | func ss(u *url.URL, i int) (*map[string]interface{}, string, error) {
function parseNaiveLink (line 413) | func parseNaiveLink(u *url.URL, i int) (*map[string]interface{}, string,...
function getTransport (line 494) | func getTransport(tp_type string, q *url.Values) map[string]interface{} {
function getTls (line 534) | func getTls(security string, q *url.Values) map[string]interface{} {
FILE: util/outJson.go
function FillOutJson (line 12) | func FillOutJson(i *model.Inbound, hostname string) error {
function addTls (line 78) | func addTls(out *map[string]interface{}, tls *model.Tls) {
function naiveOut (line 129) | func naiveOut(out *map[string]interface{}, inbound map[string]interface{...
function shadowsocksOut (line 144) | func shadowsocksOut(out *map[string]interface{}, inbound map[string]inte...
function shadowTlsOut (line 150) | func shadowTlsOut(out *map[string]interface{}, inbound map[string]interf...
function hysteriaOut (line 161) | func hysteriaOut(out *map[string]interface{}, inbound map[string]interfa...
function hysteria2Out (line 185) | func hysteria2Out(out *map[string]interface{}, inbound map[string]interf...
function tuicOut (line 201) | func tuicOut(out *map[string]interface{}, inbound map[string]interface{}) {
function vlessOut (line 217) | func vlessOut(out *map[string]interface{}, inbound map[string]interface{...
function trojanOut (line 224) | func trojanOut(out *map[string]interface{}, inbound map[string]interface...
function vmessOut (line 231) | func vmessOut(out *map[string]interface{}, inbound map[string]interface{...
FILE: util/subInfo.go
function GetHeaders (line 9) | func GetHeaders(client *model.Client, updateInterval int) []string {
FILE: util/subToJson.go
function GetExternalLink (line 14) | func GetExternalLink(url string) string {
function GetExternalSub (line 38) | func GetExternalSub(url string) ([]map[string]interface{}, error) {
FILE: web/web.go
type Server (line 31) | type Server struct
method initRouter (line 47) | func (s *Server) initRouter() (*gin.Engine, error) {
method Start (line 137) | func (s *Server) Start() (err error) {
method Stop (line 202) | func (s *Server) Stop() error {
method GetCtx (line 220) | func (s *Server) GetCtx() context.Context {
function NewServer (line 39) | func NewServer() *Server {
Condensed preview — 106 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (504K chars).
[
{
"path": ".dockerignore",
"chars": 233,
"preview": ".DS_Store\ndist/\nrelease/\nbackup/\nbin/\ndb/\nsui\nweb/html\nmain\ntmp\n.sync*\n*.tar.gz\nfrontend/node_modules\nfrontend/.vite\n\n# "
},
{
"path": ".github/FUNDING.yml",
"chars": 17,
"preview": "github: alireza0\n"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 835,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Describe the "
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 604,
"preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is"
},
{
"path": ".github/ISSUE_TEMPLATE/question-template.md",
"chars": 123,
"preview": "---\nname: Question template\nabout: Ask if it is not clear that it is a bug\ntitle: ''\nlabels: question\nassignees: ''\n\n---"
},
{
"path": ".github/dependabot.yml",
"chars": 204,
"preview": "version: 2\nupdates:\n - package-ecosystem: \"gomod\"\n directory: \"/\"\n schedule:\n interval: \"daily\"\n - package-"
},
{
"path": ".github/workflows/docker.yml",
"chars": 5157,
"preview": "name: Docker Image CI\non:\n push:\n tags:\n - \"*\"\n workflow_dispatch:\n\njobs:\n frontend-build:\n runs-on: ubunt"
},
{
"path": ".github/workflows/release.yml",
"chars": 7861,
"preview": "name: Release S-UI\n\non:\n workflow_dispatch:\n release:\n types: [published]\n push:\n branches:\n - main\n ta"
},
{
"path": ".github/workflows/windows.yml",
"chars": 4117,
"preview": "name: Build S-UI for Windows\n\non:\n workflow_dispatch:\n release:\n types: [published]\n push:\n branches:\n - m"
},
{
"path": ".gitignore",
"chars": 297,
"preview": ".DS_Store\ndist/\nrelease/\nbackup/\nbin/\ndb/\nsui\nweb/html\nmain\ntmp\n.sync*\n*.tar.gz\nfrontend/\n\n# local env files\n.env.local\n"
},
{
"path": ".gitmodules",
"chars": 104,
"preview": "[submodule \"frontend\"]\n\tpath = frontend\n\turl = https://github.com/alireza0/s-ui-frontend\n\tbranch = main\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 10287,
"preview": "# Contributing to S-UI\n\nThank you for your interest in contributing to S-UI. This document explains how to set up a deve"
},
{
"path": "Dockerfile",
"chars": 1345,
"preview": "FROM --platform=$BUILDPLATFORM node:alpine AS front-builder\nWORKDIR /app\nCOPY frontend/ ./\nRUN npm install && npm run bu"
},
{
"path": "Dockerfile.frontend-artifact",
"chars": 1204,
"preview": "FROM golang:1.25-alpine AS backend-builder\nWORKDIR /app\nARG TARGETARCH\nARG TARGETVARIANT\nENV CGO_ENABLED=1\nENV CGO_CFLAG"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 8348,
"preview": "# S-UI\n**An Advanced Web Panel • Built on SagerNet/Sing-Box**\n\n\n\ntype APIHandle"
},
{
"path": "api/apiService.go",
"chars": 9532,
"preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-"
},
{
"path": "api/apiV2Handler.go",
"chars": 2868,
"preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/commo"
},
{
"path": "api/session.go",
"chars": 1058,
"preview": "package api\n\nimport (\n\t\"encoding/gob\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n\n\t\"github.com/gin-contrib/sessions\"\n\t\""
},
{
"path": "api/utils.go",
"chars": 1701,
"preview": "package api\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n"
},
{
"path": "app/app.go",
"chars": 2292,
"preview": "package app\n\nimport (\n\t\"log\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.com/alireza0/s-ui/core\"\n\t\"github.com/alireza0/"
},
{
"path": "build.sh",
"chars": 388,
"preview": "#!/bin/sh\n\ncd frontend\nnpm i\nnpm run build\n\ncd ..\necho \"Backend\"\n\nmkdir -p web/html\nrm -fr web/html/*\ncp -R frontend/dis"
},
{
"path": "cmd/admin.go",
"chars": 1478,
"preview": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alire"
},
{
"path": "cmd/cmd.go",
"chars": 2538,
"preview": "package cmd\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime/debug\"\n\n\t\"github.com/alireza0/s-ui/cmd/migration\"\n\t\"github.com/alir"
},
{
"path": "cmd/migration/1_1.go",
"chars": 2079,
"preview": "package migration\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n\n\t\"gorm.io/go"
},
{
"path": "cmd/migration/1_2.go",
"chars": 7808,
"preview": "package migration\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/alireza0/s-ui/database/model"
},
{
"path": "cmd/migration/1_3.go",
"chars": 3964,
"preview": "package migration\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/database/model"
},
{
"path": "cmd/migration/main.go",
"chars": 1479,
"preview": "package migration\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\n\t\"gorm.io/driver/sqlite\"\n\t\"gorm.io/"
},
{
"path": "cmd/setting.go",
"chars": 5052,
"preview": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.c"
},
{
"path": "config/config.go",
"chars": 1141,
"preview": "package config\n\nimport (\n\t_ \"embed\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n//go:embed version\nvar versio"
},
{
"path": "config/name",
"chars": 4,
"preview": "s-ui"
},
{
"path": "config/version",
"chars": 5,
"preview": "1.4.0"
},
{
"path": "core/box.go",
"chars": 19118,
"preview": "package core\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"github.com/"
},
{
"path": "core/endpoint.go",
"chars": 3185,
"preview": "package core\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"github.com/sagernet"
},
{
"path": "core/log.go",
"chars": 5594,
"preview": "package core\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\tsuiLog \"github.com/alireza0/s-ui/logger\"\n\n\t\"github.com/sagernet/"
},
{
"path": "core/main.go",
"chars": 2249,
"preview": "package core\n\nimport (\n\t\"context\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\n\tsb \"github.com/sagernet/sing-box\"\n\t\"github.com/s"
},
{
"path": "core/outbound_check.go",
"chars": 748,
"preview": "package core\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\turltest \"github.com/sagernet/sing-box/common/urltest\"\n)\n\nconst checkTimeout "
},
{
"path": "core/register.go",
"chars": 4310,
"preview": "package core\n\nimport (\n\t\"github.com/sagernet/sing-box/adapter/endpoint\"\n\t\"github.com/sagernet/sing-box/adapter/inbound\"\n"
},
{
"path": "core/register_naive.go",
"chars": 248,
"preview": "//go:build with_naive_outbound\n\npackage core\n\nimport (\n\t\"github.com/sagernet/sing-box/adapter/outbound\"\n\t\"github.com/sag"
},
{
"path": "core/register_naive_stub.go",
"chars": 364,
"preview": "//go:build !with_naive_outbound\n\npackage core\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/sagernet/sing-bo"
},
{
"path": "core/tracker_conn.go",
"chars": 3010,
"preview": "package core\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/gofrs/uuid/v5\"\n\t\"github.com/sagernet/sing-box/adapter\"\n\t\""
},
{
"path": "core/tracker_stats.go",
"chars": 3841,
"preview": "package core\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n\n\t\"github.com/sager"
},
{
"path": "cronjob/WALCheckpointJob.go",
"chars": 405,
"preview": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/logger\"\n)\n\ntype WALCheckpointJ"
},
{
"path": "cronjob/checkCoreJob.go",
"chars": 246,
"preview": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/service\"\n)\n\ntype CheckCoreJob struct {\n\tservice.ConfigService\n}\n\nfu"
},
{
"path": "cronjob/cronJob.go",
"chars": 836,
"preview": "package cronjob\n\nimport (\n\t\"time\"\n\n\t\"github.com/robfig/cron/v3\"\n)\n\ntype CronJob struct {\n\tcron *cron.Cron\n}\n\nfunc NewCro"
},
{
"path": "cronjob/delStatsJob.go",
"chars": 495,
"preview": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n)\n\ntype DelStatsJob str"
},
{
"path": "cronjob/depleteJob.go",
"chars": 620,
"preview": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/"
},
{
"path": "cronjob/statsJob.go",
"chars": 422,
"preview": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n)\n\ntype StatsJob struct"
},
{
"path": "database/backup.go",
"chars": 7273,
"preview": "package database\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime/multipart\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscal"
},
{
"path": "database/db.go",
"chars": 1830,
"preview": "package database\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.com/al"
},
{
"path": "database/model/endpoints.go",
"chars": 1504,
"preview": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Endpoint struct {\n\tId uint `json:\"id\" form:\"id\" gorm:\"p"
},
{
"path": "database/model/inbounds.go",
"chars": 2440,
"preview": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Inbound struct {\n\tId uint `json:\"id\" form:\"id\" gorm:\"primaryKey;aut"
},
{
"path": "database/model/model.go",
"chars": 2844,
"preview": "package model\n\nimport \"encoding/json\"\n\ntype Setting struct {\n\tId uint `json:\"id\" form:\"id\" gorm:\"primaryKey;autoInc"
},
{
"path": "database/model/outbounds.go",
"chars": 1299,
"preview": "package model\n\nimport \"encoding/json\"\n\ntype Outbound struct {\n\tId uint `json:\"id\" form:\"id\" gorm:\"primar"
},
{
"path": "database/model/services.go",
"chars": 2053,
"preview": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Service struct {\n\tId uint `json:\"id\" form:\"id\" gorm:\"primaryKey;aut"
},
{
"path": "docker-build-test.sh",
"chars": 977,
"preview": "#!/usr/bin/env bash\n# Test Docker multi-platform build (linux/amd64, 386, arm64, arm/v7, arm/v6)\n# Requires: frontend_di"
},
{
"path": "docker-compose.yml",
"chars": 350,
"preview": "---\nservices:\n s-ui:\n image: alireza7/s-ui\n container_name: s-ui\n hostname: \"s-ui\"\n volumes:\n - \"./db:"
},
{
"path": "entrypoint.sh",
"chars": 111,
"preview": "#!/bin/sh\n\nDB_PATH=\"${SUI_DB_FOLDER:-/app/db}/s-ui.db\"\nif [ -f \"$DB_PATH\" ]; then\n\t./sui migrate\nfi\n\nexec ./sui"
},
{
"path": "go.mod",
"chars": 11460,
"preview": "module github.com/alireza0/s-ui\n\ngo 1.25.7\n\nrequire (\n\tgithub.com/gin-contrib/gzip v1.2.5\n\tgithub.com/gin-contrib/sessio"
},
{
"path": "go.sum",
"chars": 48559,
"preview": "code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=\ncode.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYs"
},
{
"path": "install.sh",
"chars": 7285,
"preview": "#!/bin/bash\n\nred='\\033[0;31m'\ngreen='\\033[0;32m'\nyellow='\\033[0;33m'\nplain='\\033[0m'\n\ncur_dir=$(pwd)\n\n# check root\n[[ $E"
},
{
"path": "logger/logger.go",
"chars": 2984,
"preview": "package logger\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/op/go-logging\"\n)\n\nvar (\n\tlogger *logging.Logger\n\tlogBuffe"
},
{
"path": "main.go",
"chars": 612,
"preview": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"github.com/alireza0/s-ui/app\"\n\t\"github.com/alireza0/s-ui/"
},
{
"path": "middleware/domainValidator.go",
"chars": 420,
"preview": "package middleware\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc DomainValidator(domain s"
},
{
"path": "network/auto_https_conn.go",
"chars": 1189,
"preview": "package network\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype AutoHttpsConn struct {\n\tnet.Conn\n\n"
},
{
"path": "network/auto_https_listener.go",
"chars": 367,
"preview": "package network\n\nimport \"net\"\n\ntype AutoHttpsListener struct {\n\tnet.Listener\n}\n\nfunc NewAutoHttpsListener(listener net.L"
},
{
"path": "runSUI.sh",
"chars": 50,
"preview": "./build.sh\nSUI_DB_FOLDER=\"db\" SUI_DEBUG=true ./sui"
},
{
"path": "s-ui.service",
"chars": 232,
"preview": "[Unit]\nDescription=s-ui Service\nAfter=network.target\nWants=network.target\n\n[Service]\nType=simple\nWorkingDirectory=/usr/l"
},
{
"path": "s-ui.sh",
"chars": 26066,
"preview": "#!/bin/bash\n\nred='\\033[0;31m'\ngreen='\\033[0;32m'\nyellow='\\033[0;33m'\nplain='\\033[0m'\n\nfunction LOGD() {\n echo -e \"${y"
},
{
"path": "service/client.go",
"chars": 14372,
"preview": "package service\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.co"
},
{
"path": "service/config.go",
"chars": 7118,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/core\"\n\t\"github.com/ali"
},
{
"path": "service/endpoints.go",
"chars": 3114,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/databa"
},
{
"path": "service/inbounds.go",
"chars": 9128,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/al"
},
{
"path": "service/outbounds.go",
"chars": 2603,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/databa"
},
{
"path": "service/panel.go",
"chars": 498,
"preview": "package service\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n)\n\ntype PanelService s"
},
{
"path": "service/server.go",
"chars": 7866,
"preview": "package service\n\nimport (\n\t\"encoding/base64\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/"
},
{
"path": "service/services.go",
"chars": 3269,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/databa"
},
{
"path": "service/setting.go",
"chars": 9648,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/co"
},
{
"path": "service/stats.go",
"chars": 3848,
"preview": "package service\n\nimport (\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/database/mode"
},
{
"path": "service/tls.go",
"chars": 2405,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/database/mod"
},
{
"path": "service/user.go",
"chars": 4303,
"preview": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/data"
},
{
"path": "service/warp.go",
"chars": 5647,
"preview": "package service\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time"
},
{
"path": "sub/clashService.go",
"chars": 10100,
"preview": "package sub\n\nimport (\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n\t\"github.com/al"
},
{
"path": "sub/jsonService.go",
"chars": 8554,
"preview": "package sub\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-u"
},
{
"path": "sub/linkService.go",
"chars": 1715,
"preview": "package sub\n\nimport (\n\t\"encoding/json\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util\"\n)"
},
{
"path": "sub/sub.go",
"chars": 2792,
"preview": "package sub\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/alireza0/s-ui/config\"\n\t"
},
{
"path": "sub/subHandler.go",
"chars": 1631,
"preview": "package sub\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n\n\t\"github.com/gin-gonic/gin"
},
{
"path": "sub/subService.go",
"chars": 2568,
"preview": "package sub\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/al"
},
{
"path": "util/base64.go",
"chars": 445,
"preview": "package util\n\nimport \"encoding/base64\"\n\n// Function to return decoded bytes if a string is Base64 encoded\nfunc StrOrBase"
},
{
"path": "util/common/array.go",
"chars": 896,
"preview": "package common\n\n// UnionUintArray returns a new unique slice that contains all elements from both input slices\nfunc Unio"
},
{
"path": "util/common/err.go",
"chars": 460,
"preview": "package common\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n)\n\nfunc NewErrorf(format string, a ...inte"
},
{
"path": "util/common/random.go",
"chars": 1248,
"preview": "package common\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"math/big\"\n\tmrand \"math/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\tallSeq []rune = ["
},
{
"path": "util/genLink.go",
"chars": 17804,
"preview": "package util\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/data"
},
{
"path": "util/linkToJson.go",
"chars": 14224,
"preview": "package util\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/util/"
},
{
"path": "util/outJson.go",
"chars": 6245,
"preview": "package util\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"github.com/alireza0/s-ui/database/mo"
},
{
"path": "util/subInfo.go",
"chars": 429,
"preview": "package util\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n)\n\nfunc GetHeaders(client *model.Client, updat"
},
{
"path": "util/subToJson.go",
"chars": 2138,
"preview": "package util\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/logger\"\n\t"
},
{
"path": "web/web.go",
"chars": 4643,
"preview": "package web\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"html/template\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"strconv\"\n\t\""
},
{
"path": "windows/README.md",
"chars": 662,
"preview": "# Windows Files\n\nThis directory contains all Windows-specific files for S-UI.\n\n## Available Files:\n\n- **s-ui-windows.xml"
},
{
"path": "windows/build-windows.bat",
"chars": 1622,
"preview": "@echo off\nsetlocal enabledelayedexpansion\n\necho Building S-UI for Windows...\n\ncd /d \"%~dp0\"\n\nREM Check if Go is installe"
},
{
"path": "windows/build-windows.ps1",
"chars": 4254,
"preview": "# PowerShell script for building S-UI on Windows\nparam(\n [string]$Architecture = \"amd64\",\n [switch]$NoCGO,\n [sw"
},
{
"path": "windows/install-windows.bat",
"chars": 6276,
"preview": "@echo off\nsetlocal enabledelayedexpansion\n\necho ========================================\necho S-UI Windows Installer\nech"
},
{
"path": "windows/s-ui-windows.bat",
"chars": 5564,
"preview": "@echo off\nsetlocal enabledelayedexpansion\n\nREM S-UI Windows Control Script\nREM This script provides a menu-driven interf"
},
{
"path": "windows/s-ui-windows.xml",
"chars": 737,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<service>\n <id>s-ui</id>\n <name>S-UI Proxy Panel</name>\n <description>S-UI is "
},
{
"path": "windows/uninstall-windows.bat",
"chars": 3405,
"preview": "@echo off\nsetlocal enabledelayedexpansion\n\necho ========================================\necho S-UI Windows Uninstaller\ne"
}
]
About this extraction
This page contains the full source code of the alireza0/s-ui GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 106 files (448.7 KB), approximately 143.4k tokens, and a symbol index with 504 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.