[
  {
    "path": ".dockerignore",
    "content": ".DS_Store\ndist/\nrelease/\nbackup/\nbin/\ndb/\nsui\nweb/html\nmain\ntmp\n.sync*\n*.tar.gz\nfrontend/node_modules\nfrontend/.vite\n\n# local env files\n.env.local\n.env.*.local\n\n# Log files\n*.log*\n.cache\n\n# Editor directories and files\n.idea\n.vscode\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: alireza0\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS]\n - Browser [e.g. chrome, safari]\n - Version [e.g. 22]\n\n**Smartphone (please complete the following information):**\n - Device: [e.g. iPhone6]\n - OS: [e.g. iOS8.1]\n - Browser [e.g. stock browser, safari]\n - Version [e.g. 22]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question-template.md",
    "content": "---\nname: Question template\nabout: Ask if it is not clear that it is a bug\ntitle: ''\nlabels: question\nassignees: ''\n\n---\n\n\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"gomod\"\n    directory: \"/\"\n    schedule:\n      interval: \"daily\"\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"daily\""
  },
  {
    "path": ".github/workflows/docker.yml",
    "content": "name: Docker Image CI\non:\n  push:\n    tags:\n      - \"*\"\n  workflow_dispatch:\n\njobs:\n  frontend-build:\n    runs-on: ubuntu-24.04\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6.0.2\n        with:\n          submodules: recursive\n      - name: Set up Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: 24\n      - name: Install dependencies and build frontend\n        run: |\n          cd frontend\n          npm install\n          npm run build\n      - name: Upload frontend build artifact\n        uses: actions/upload-artifact@v7\n        with:\n          name: frontend-dist\n          path: frontend/dist/\n\n  build:\n    needs: frontend-build\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - { platform: linux/amd64 }\n          - { platform: linux/386 }\n          - { platform: linux/arm64/v8 }\n          - { platform: linux/arm/v7 }\n          - { platform: linux/arm/v6 }\n    runs-on: ubuntu-24.04\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6.0.2\n      - name: Download frontend build artifact\n        uses: actions/download-artifact@v8\n        with:\n          name: frontend-dist\n          path: frontend_dist\n      - name: Prepare\n        run: |\n          platform=\"${{ matrix.platform }}\"\n          echo \"PLATFORM_PAIR=${platform//\\//-}\" >> $GITHUB_ENV\n      - name: Docker meta\n        id: meta\n        uses: docker/metadata-action@v6\n        with:\n          images: |\n            alireza7/s-ui\n            ghcr.io/alireza0/s-ui\n          tags: |\n            type=ref,event=branch\n            type=ref,event=tag\n            type=pep440,pattern={{version}}\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v4\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v4\n      - name: Cache Docker layers\n        uses: actions/cache@v5\n        with:\n          path: /tmp/.buildx-cache\n          key: ${{ runner.os }}-buildx-${{ matrix.platform }}-${{ github.sha }}\n          restore-keys: |\n            ${{ runner.os }}-buildx-${{ matrix.platform }}-\n      - name: Login to Docker Hub\n        uses: docker/login-action@v4\n        with:\n          username: ${{ secrets.DOCKER_HUB_USERNAME }}\n          password: ${{ secrets.DOCKER_HUB_TOKEN }}\n      - name: Login to GHCR\n        uses: docker/login-action@v4\n        with:\n          registry: ghcr.io\n          username: ${{ github.repository_owner }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n      - name: Build and push by digest\n        id: build\n        uses: docker/build-push-action@v7\n        with:\n          context: .\n          file: Dockerfile.frontend-artifact\n          platforms: ${{ matrix.platform }}\n          labels: ${{ steps.meta.outputs.labels }}\n          tags: |\n            alireza7/s-ui\n            ghcr.io/alireza0/s-ui\n          cache-from: type=local,src=/tmp/.buildx-cache\n          cache-to: type=local,dest=/tmp/.buildx-cache,mode=max\n          outputs: type=image,push-by-digest=true,name-canonical=true,push=true\n      - name: Export digest\n        run: |\n          mkdir -p ${{ runner.temp }}/digests\n          digest=\"${{ steps.build.outputs.digest }}\"\n          echo \"${digest#sha256:}\" > \"${{ runner.temp }}/digests/${digest#sha256:}\"\n      - name: Upload digest\n        uses: actions/upload-artifact@v7\n        with:\n          name: digests-${{ env.PLATFORM_PAIR }}\n          path: ${{ runner.temp }}/digests/*\n          if-no-files-found: error\n          retention-days: 1\n\n  merge:\n    needs: build\n    runs-on: ubuntu-24.04\n    steps:\n      - name: Download digests\n        uses: actions/download-artifact@v8\n        with:\n          path: ${{ runner.temp }}/digests\n          pattern: digests-*\n          merge-multiple: true\n      - name: Login to Docker Hub\n        uses: docker/login-action@v4\n        with:\n          username: ${{ secrets.DOCKER_HUB_USERNAME }}\n          password: ${{ secrets.DOCKER_HUB_TOKEN }}\n      - name: Login to GHCR\n        uses: docker/login-action@v4\n        with:\n          registry: ghcr.io\n          username: ${{ github.repository_owner }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v4\n      - name: Docker meta\n        id: meta\n        uses: docker/metadata-action@v6\n        with:\n          images: |\n            alireza7/s-ui\n            ghcr.io/alireza0/s-ui\n          tags: |\n            type=ref,event=branch\n            type=ref,event=tag\n            type=pep440,pattern={{version}}\n      - name: Create manifest list and push\n        env:\n          DOCKER_METADATA_OUTPUT_JSON: ${{ steps.meta.outputs.json }}\n        working-directory: ${{ runner.temp }}/digests\n        run: |\n          set -e\n          for img in alireza7/s-ui ghcr.io/alireza0/s-ui; do\n            TAGS_ARGS=$(echo \"$DOCKER_METADATA_OUTPUT_JSON\" | jq -cr --arg img \"$img\" '.tags | map(select(startswith($img))) | map(\"-t \" + .) | join(\" \")')\n            DIGEST_REFS=$(for f in *; do echo -n \"${img}@sha256:$(cat \"$f\") \"; done)\n            docker buildx imagetools create $TAGS_ARGS $DIGEST_REFS\n          done\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release S-UI\n\non:\n  workflow_dispatch:\n  release:\n    types: [published]\n  push:\n    branches:\n      - main\n    tags:\n      - \"*\"\n    paths:\n      - '.github/workflows/release.yml'\n      - 'frontend/**'\n      - '**.sh'\n      - '**.go'\n      - 'go.mod'\n      - 'go.sum'\n      - 's-ui.service'\n\nenv:\n  NODE_VERSION: \"24\"\n  CRONET_GO_VERSION: \"cba7b9ac0399055aa49fbdc57c03c374f58e1597\"\n  CRONET_GO_REPO: https://github.com/sagernet/cronet-go.git\n  BOOTLIN_BASE_URL: https://toolchains.bootlin.com/downloads/releases/toolchains\n  CHROMIUM_CACHE_KEY_SUFFIX: musl-cba7b9ac0399055aa49fbdc57c03c374f58e1597\n\njobs:\n  build-frontend:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repository (frontend only)\n        uses: actions/checkout@v6.0.2\n        with:\n          submodules: recursive\n          fetch-depth: 1\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: ${{ env.NODE_VERSION }}\n          cache: 'npm'\n          cache-dependency-path: frontend/package-lock.json\n\n      - name: Build frontend\n        run: |\n          cd frontend\n          npm ci\n          npm run build\n          cd ..\n\n      - name: Upload frontend dist\n        uses: actions/upload-artifact@v7\n        with:\n          name: frontend-dist\n          path: frontend/dist/\n\n  build-linux:\n    name: build-${{ matrix.platform }}\n    needs: build-frontend\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - { platform: amd64, arch: amd64, bootlin: x86-64, naive: true }\n          - { platform: arm64, arch: arm64, bootlin: aarch64, naive: true }\n          - { platform: armv7, arch: arm, goarm: \"7\", bootlin: armv7-eabihf, naive: true }\n          - { platform: armv6, arch: arm, goarm: \"6\", bootlin: armv6-eabihf, naive: true }\n          - { platform: armv5, arch: arm, goarm: \"5\", bootlin: armv5-eabi, naive: false }\n          - { platform: \"386\", arch: \"386\", bootlin: x86-i686, naive: true }\n          - { platform: s390x, arch: s390x, bootlin: s390x-z13, naive: false }\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6.0.2\n\n      - name: Download frontend dist\n        uses: actions/download-artifact@v8\n        with:\n          name: frontend-dist\n          path: web/html\n\n      - name: Setup Go\n        uses: actions/setup-go@v6\n        with:\n          cache: false\n          go-version-file: go.mod\n\n      # Naive platforms: use cronet toolchain only (no Bootlin).\n      - name: Clone cronet-go (cronet toolchain for naive)\n        if: matrix.naive\n        run: |\n          set -e\n          git init ~/cronet-go\n          git -C ~/cronet-go remote add origin ${{ env.CRONET_GO_REPO }}\n          git -C ~/cronet-go fetch --depth=1 origin \"${{ env.CRONET_GO_VERSION }}\"\n          git -C ~/cronet-go checkout FETCH_HEAD\n          git -C ~/cronet-go submodule update --init --recursive --depth=1\n\n      - name: Regenerate Debian keyring (cronet sysroot)\n        if: matrix.naive\n        run: |\n          set -e\n          rm -f ~/cronet-go/naiveproxy/src/build/linux/sysroot_scripts/keyring.gpg\n          cd ~/cronet-go\n          GPG_TTY=/dev/null ./naiveproxy/src/build/linux/sysroot_scripts/generate_keyring.sh\n\n      - name: Cache Chromium toolchain\n        if: matrix.naive\n        id: cache-chromium-toolchain\n        uses: actions/cache@v5\n        with:\n          path: |\n            ~/cronet-go/naiveproxy/src/third_party/llvm-build/\n            ~/cronet-go/naiveproxy/src/gn/out/\n            ~/cronet-go/naiveproxy/src/chrome/build/pgo_profiles/\n            ~/cronet-go/naiveproxy/src/out/sysroot-build/\n          key: chromium-toolchain-${{ matrix.platform }}-${{ env.CHROMIUM_CACHE_KEY_SUFFIX }}\n\n      - name: Build cronet lib and set toolchain env (CC, CXX, CGO_LDFLAGS, PATH)\n        if: matrix.naive\n        run: |\n          set -e\n          cd ~/cronet-go\n          go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl download-toolchain\n          go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl env | while IFS= read -r line; do\n            line=\"${line#export }\"\n            [[ -z \"$line\" ]] && continue\n            echo \"$line\" >> $GITHUB_ENV\n          done\n\n      - name: Set Go build env (all platforms)\n        run: |\n          echo \"CGO_ENABLED=1\" >> $GITHUB_ENV\n          echo \"GOOS=linux\" >> $GITHUB_ENV\n          echo \"GOARCH=${{ matrix.arch }}\" >> $GITHUB_ENV\n          if [ -n \"${{ matrix.goarm }}\" ]; then echo \"GOARM=${{ matrix.goarm }}\" >> $GITHUB_ENV; fi\n\n      # Non-naive platforms only: Bootlin musl (armv5, s390x).\n      - name: Set up Bootlin musl (armv5, s390x)\n        if: ${{ matrix.naive != true }}\n        run: |\n          set -e\n          BOOTLIN_ARCH=\"${{ matrix.bootlin }}\"\n          echo \"Resolving Bootlin musl toolchain for arch=$BOOTLIN_ARCH (platform=${{ matrix.platform }})\"\n          TARBALL_BASE=\"${{ env.BOOTLIN_BASE_URL }}/$BOOTLIN_ARCH/tarballs/\"\n          TARBALL_URL=$(curl -fsSL \"$TARBALL_BASE\" | grep -oE \"${BOOTLIN_ARCH}--musl--stable-[^\\\"]+\\\\.tar\\\\.xz\" | sort -r | head -n1)\n          [ -z \"$TARBALL_URL\" ] && { echo \"Failed to locate Bootlin musl toolchain for arch=$BOOTLIN_ARCH\" >&2; exit 1; }\n          echo \"Downloading: $TARBALL_URL\"\n          cd /tmp\n          curl -fL -sS -o \"$(basename \"$TARBALL_URL\")\" \"$TARBALL_BASE/$TARBALL_URL\"\n          tar -xf \"$(basename \"$TARBALL_URL\")\"\n          TOOLCHAIN_DIR=$(find . -maxdepth 1 -type d -name \"${BOOTLIN_ARCH}--musl--stable-*\" | head -n1)\n          TOOLCHAIN_DIR=\"$(realpath \"$TOOLCHAIN_DIR\")\"\n          BIN_DIR=\"$TOOLCHAIN_DIR/bin\"\n          echo \"PATH=$BIN_DIR:$PATH\" >> $GITHUB_ENV\n          CC=$(find \"$BIN_DIR\" -maxdepth 1 \\( -name '*-gcc.br_real' -o -name '*-gcc' \\) -type f -executable 2>/dev/null | grep -v g++ | head -n1)\n          [ -z \"$CC\" ] && { echo \"No gcc found in $BIN_DIR\" >&2; exit 1; }\n          echo \"CC=$(realpath \"$CC\")\" >> $GITHUB_ENV\n          SYSROOT=\"\"\n          F=$(find \"$TOOLCHAIN_DIR\" -name \"libc-header-start.h\" 2>/dev/null | head -1)\n          if [ -n \"$F\" ]; then SYSROOT=$(dirname \"$(dirname \"$(dirname \"$(dirname \"$F\")\")\")\"); fi\n          if [ -n \"$SYSROOT\" ] && [ -d \"$SYSROOT\" ]; then\n            echo \"CGO_CFLAGS=--sysroot=$SYSROOT\" >> $GITHUB_ENV\n            echo \"CGO_LDFLAGS=--sysroot=$SYSROOT -static\" >> $GITHUB_ENV\n          fi\n\n      - name: Build s-ui\n        run: |\n          set -e\n          BUILD_TAGS=\"with_quic,with_grpc,with_utls,with_acme,with_gvisor,badlinkname,tfogo_checklinkname0\"\n          [ \"${{ matrix.naive }}\" = \"true\" ] && BUILD_TAGS=\"${BUILD_TAGS},with_naive_outbound,with_musl\"\n          go build -ldflags=\"-w -s -checklinkname=0 -linkmode external -extldflags '-static'\" -tags \"$BUILD_TAGS\" -o sui main.go\n          file sui\n          ldd sui 2>/dev/null || echo \"Static binary confirmed\"\n\n          mkdir s-ui\n          cp sui s-ui/\n          cp s-ui.service s-ui/\n          cp s-ui.sh s-ui/\n\n      - name: Package\n        run: tar -zcvf s-ui-linux-${{ matrix.platform }}.tar.gz s-ui\n\n      - name: Upload artifact\n        uses: actions/upload-artifact@v7\n        with:\n          name: s-ui-linux-${{ matrix.platform }}\n          path: ./s-ui-linux-${{ matrix.platform }}.tar.gz\n          retention-days: 30\n\n      - name: Upload to Release\n        uses: svenstaro/upload-release-action@v2\n        if: |\n          (github.event_name == 'release' && github.event.action == 'published') ||\n          (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))\n        with:\n          repo_token: ${{ secrets.GITHUB_TOKEN }}\n          tag: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref_name }}\n          file: s-ui-linux-${{ matrix.platform }}.tar.gz\n          asset_name: s-ui-linux-${{ matrix.platform }}.tar.gz\n          prerelease: true\n          overwrite: true\n"
  },
  {
    "path": ".github/workflows/windows.yml",
    "content": "name: Build S-UI for Windows\n\non:\n  workflow_dispatch:\n  release:\n    types: [published]\n  push:\n    branches:\n      - main\n    tags:\n      - \"*\"\n    paths:\n      - '.github/workflows/windows.yml'\n      - 'frontend/**'\n      - '**.go'\n      - 'go.mod'\n      - 'go.sum'\n      - 'windows/**'\n\nenv:\n  NODE_VERSION: \"24\"\n  TAGS: \"with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego,badlinkname,tfogo_checklinkname0\"\n  LIBCRONET_BASE_URL: \"https://github.com/SagerNet/cronet-go/releases/latest/download\"\n\njobs:\n  build-frontend:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6.0.2\n        with:\n          submodules: recursive\n          fetch-depth: 1\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: ${{ env.NODE_VERSION }}\n          registry-url: 'https://registry.npmjs.org'\n\n      - name: Build frontend\n        run: |\n          cd frontend\n          npm install\n          npm run build\n          cd ..\n\n      - name: Upload frontend artifact\n        uses: actions/upload-artifact@v7\n        with:\n          name: frontend-dist\n          path: frontend/dist\n          retention-days: 1\n\n  build-windows:\n    needs: build-frontend\n    name: build-windows-${{ matrix.arch }}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - { arch: amd64, runner: windows-latest, cgo: \"1\" }\n          - { arch: arm64, runner: ubuntu-latest, cgo: \"0\" }\n    runs-on: ${{ matrix.runner }}\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6.0.2\n\n      - name: Download frontend artifact\n        uses: actions/download-artifact@v8\n        with:\n          name: frontend-dist\n          path: web/html\n\n      - name: Setup Go\n        uses: actions/setup-go@v6\n        with:\n          cache: false\n          go-version-file: go.mod\n\n      - name: Install zip for Windows\n        if: matrix.arch == 'amd64'\n        shell: powershell\n        run: |\n          # Install Chocolatey if not available\n          if (!(Get-Command choco -ErrorAction SilentlyContinue)) {\n            Set-ExecutionPolicy Bypass -Scope Process -Force\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072\n            iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))\n          }\n          # Install zip\n          choco install zip -y\n\n      - name: Build s-ui\n        shell: bash\n        run: |\n          export CGO_ENABLED=${{ matrix.cgo }}\n          export GOOS=windows\n          export GOARCH=${{ matrix.arch }}\n          \n          echo \"Building for Windows ${{ matrix.arch }}\"\n          go version\n          go env GOOS GOARCH\n          \n          go build -ldflags=\"-w -s -checklinkname=0\" -tags \"${{ env.TAGS }}\" -o sui.exe main.go\n          file sui.exe\n          \n          mkdir s-ui-windows\n          cp sui.exe s-ui-windows/\n          cp -r windows/* s-ui-windows/\n\n      - name: Download libcronet-go\n        shell: bash\n        run: |\n          curl -qsL -o s-ui-windows/libcronet.dll ${{ env.LIBCRONET_BASE_URL }}/libcronet-windows-${{ matrix.arch }}.dll\n\n      - name: Package\n        shell: bash\n        run: |\n          zip -r \"s-ui-windows-${{ matrix.arch }}.zip\" s-ui-windows\n\n      - name: Upload files to Artifacts\n        uses: actions/upload-artifact@v7\n        with:\n          name: s-ui-windows-${{ matrix.arch }}\n          path: ./s-ui-windows-${{ matrix.arch }}.zip\n          retention-days: 30\n\n      - name: Upload to Release\n        uses: svenstaro/upload-release-action@v2\n        if: |\n          (github.event_name == 'release' && github.event.action == 'published') ||\n          (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))\n        with:\n          repo_token: ${{ secrets.GITHUB_TOKEN }}\n          tag: ${{ github.ref }}\n          file: s-ui-windows-${{ matrix.arch }}.zip\n          asset_name: s-ui-windows-${{ matrix.arch }}.zip\n          prerelease: true\n          overwrite: true\n"
  },
  {
    "path": ".gitignore",
    "content": ".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.env.*.local\n\n# Log files\n*.log*\n.cache\n\n# Windows build artifacts\n*.exe\n*.zip\ns-ui-windows/\nsui-*.exe\nsui-*.zip\nwindows/sui-*.exe\n\n# Editor directories and files\n.idea\n.vscode\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"frontend\"]\n\tpath = frontend\n\turl = https://github.com/alireza0/s-ui-frontend\n\tbranch = main\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to S-UI\n\nThank 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.\n\n## Table of Contents\n\n- [Code of Conduct](#code-of-conduct)\n- [Development Environment Setup](#development-environment-setup)\n- [Coding Conventions and Style Guide](#coding-conventions-and-style-guide)\n- [Testing](#testing)\n- [Features That Need Help](#features-that-need-help)\n- [Pull Request Process](#pull-request-process)\n- [Adding This Guide in Your Repository](#adding-this-guide-in-your-repository)\n- [Reporting Bugs and Requesting Features](#reporting-bugs-and-requesting-features)\n\n---\n\n## Code of Conduct\n\nPlease be respectful and constructive when interacting with maintainers and other contributors. This project is for personal learning and communication; use it responsibly and legally.\n\n---\n\n## Development Environment Setup\n\n### Prerequisites\n\n- **Go**: 1.25 or later (see `go.mod` for the exact version).\n- **Git**: For cloning and submodules.\n- **C compiler**: Required for CGO (e.g. `gcc`, `musl-dev` on Alpine).\n- **Node.js** (optional): Only if you plan to work on or rebuild the frontend. The repo can be run with pre-built frontend assets.\n\n### Clone and Submodules\n\n```bash\ngit clone https://github.com/alireza0/s-ui\ncd s-ui\ngit submodule update --init --recursive\n```\n\nThe **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).\n\n### Backend-Only Development (quickest)\n\n1. Build and run with the provided script (builds backend and runs with debug + local DB):\n\n   ```bash\n   ./runSUI.sh\n   ```\n\n   This runs `./build.sh` then `SUI_DB_FOLDER=\"db\" SUI_DEBUG=true ./sui`.\n\n2. Or build manually:\n\n   ```bash\n   ./build.sh\n   SUI_DB_FOLDER=db SUI_DEBUG=true ./sui\n   ```\n\n   Default panel: **http://localhost:2095/app/** (user: `admin`, password: `admin` — change in production).\n\n### Full Stack (Backend + Frontend)\n\n1. **Frontend** (separate repo in submodule):\n\n   ```bash\n   cd frontend\n   npm install\n   npm run build\n   cd ..\n   ```\n\n2. **Replace web assets and build backend**:\n\n   ```bash\n   mkdir -p web/html\n   rm -rf web/html/*\n   cp -R frontend/dist/* web/html/\n   go build -ldflags \"-w -s\" -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor\" -o sui main.go\n   ```\n\n3. Run:\n\n   ```bash\n   SUI_DB_FOLDER=db SUI_DEBUG=true ./sui\n   ```\n\n### Build Tags\n\nThe backend is built with these tags for full functionality:\n\n- `with_quic`, `with_grpc`, `with_utls`, `with_acme`, `with_gvisor`\n\nUse the same tags when building locally if you need feature parity with releases.\n\n### Environment Variables (development)\n\n| Variable       | Description                    | Example   |\n|----------------|--------------------------------|-----------|\n| `SUI_DB_FOLDER`| Directory for SQLite DB files  | `db`      |\n| `SUI_DEBUG`    | Enable debug mode              | `true`    |\n| `SUI_LOG_LEVEL`| Log level                      | `debug`   |\n| `SUI_BIN_FOLDER` | Directory for binaries       | `bin`     |\n\n### Docker (optional)\n\n```bash\ngit clone https://github.com/alireza0/s-ui\ncd s-ui\ngit submodule update --init --recursive\ndocker build -t s-ui .\n# or: docker compose up -d\n```\n\n---\n\n## Coding Conventions and Style Guide\n\n### General\n\n- Write clear, maintainable code. Prefer small, focused functions and packages.\n- Comment non-obvious logic and public APIs.\n- Handle errors explicitly; avoid ignoring `err` unless intentional.\n\n### Go Style\n\n- Follow **standard Go style** and **[Effective Go](https://go.dev/doc/effective_go)**.\n- Run **gofmt** (or **goimports**) before committing:\n\n  ```bash\n  gofmt -w .\n  # or: goimports -w .\n  ```\n\n- Use **camelCase** for unexported names and **PascalCase** for exported names.\n- Keep package names short and lowercase (e.g. `api`, `service`, `util`).\n- Group imports: standard library, then third-party, then project imports (as in existing files).\n\n### Project Structure Conventions\n\n- **`api/`**: HTTP handlers and API routing (e.g. `apiHandler.go`, `apiV2Handler.go`).\n- **`service/`**: Business logic and panel/core operations.\n- **`database/model/`**: GORM models and DB entities.\n- **`util/`**: Shared utilities (e.g. link/sub conversion, JSON).\n- **`core/`**: sing-box integration and core runtime.\n- **`sub/`**: Subscription (link/json) handling.\n\nWhen adding new features, place code in the appropriate layer (handler → service → model/util) and avoid circular dependencies.\n\n### Naming and Patterns\n\n- Handlers: suffix `Handler` (e.g. `APIHandler`, `APIv2Handler`).\n- Services: suffix `Service` or use package name (e.g. `ApiService`, `LinkService`).\n- Models: clear struct names with JSON/gorm tags (see `database/model/`).\n\n---\n\n## Testing\n\n### Current State\n\n- The project does not yet have a formal test suite (no `*_test.go` files in the repo).\n- CI currently focuses on **builds** (e.g. `release.yml`) rather than automated tests.\n\n### What You Can Do Now\n\n1. **Build verification**: Before submitting a PR, ensure the project builds:\n\n   ```bash\n   go build -ldflags \"-w -s\" -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor\" -o sui main.go\n   ```\n\n2. **Manual testing**: Run with `./runSUI.sh`, test the changed area (panel, API, subscription, etc.).\n\n3. **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.\n\n### Running the Linter (optional)\n\n```bash\ngo vet ./...\n# Optional: staticcheck, golangci-lint, etc.\n```\n\n---\n\n## Features That Need Help\n\nCommunity help is especially valuable in these areas. Check the [Issues](https://github.com/alireza0/s-ui/issues) for current tasks and ideas.\n\n### High-Value Areas\n\n- **Multi-inbound per user**: Core differentiator of S-UI; improvements to UX, docs, and robustness are welcome.\n- **API (v1 and v2)**: Completeness, consistency, and documentation (see [API Documentation](https://github.com/alireza0/s-ui/wiki/API-Documentation)).\n- **Subscription service**: Link conversion, JSON subscription, and info endpoints (`sub/`, `util/`).\n- **Testing**: Adding unit and integration tests for critical paths.\n- **Documentation**: User docs, API examples, and contribution docs (like this file).\n- **Platform support**: macOS is experimental; Windows and Linux improvements are welcome (see `windows/` and `.github/workflows/`).\n\n### How to Find Tasks\n\n- **Good first issue**: Look for issues labeled `good first issue` or `help wanted`.\n- **Feature requests**: [Feature request template](.github/ISSUE_TEMPLATE/feature_request.md).\n- **Bugs**: [Bug report template](.github/ISSUE_TEMPLATE/bug_report.md).\n\nIf you want to work on a larger feature, open an issue first to discuss approach and avoid duplicate work.\n\n---\n\n## Pull Request Process\n\n1. **Fork and branch**\n\n   - Fork the repository on GitHub.\n   - Create a branch from `main`: e.g. `git checkout -b fix/issue-123` or `feature/sub-improvements`.\n\n2. **Make your changes**\n\n   - Follow the [Coding Conventions](#coding-conventions-and-style-guide).\n   - Run `gofmt` and ensure the project builds (see [Testing](#testing)).\n   - Keep commits focused and messages clear (e.g. \"Fix link conversion for VMess\", \"Add tests for outJson\").\n\n3. **Push and open a PR**\n\n   - Push your branch and open a Pull Request against `main`.\n   - Use the PR description to explain:\n     - What problem or feature the PR addresses.\n     - What you changed and how to verify it.\n   - Reference any related issue (e.g. \"Fixes #123\").\n\n4. **Review and CI**\n\n   - Maintainers will review your code. CI (e.g. build workflows) must pass.\n   - Address feedback by pushing new commits to the same branch.\n\n5. **Merge**\n\n   - Once approved and CI is green, a maintainer will merge your PR. Thank you for contributing!\n\n### PR Guidelines\n\n- Prefer **small, reviewable PRs**. Split large features into logical steps.\n- Avoid unrelated changes (e.g. formatting-only or refactors in a feature PR).\n- Ensure your branch is up to date with `main` before submitting (rebase or merge as the project prefers).\n\n---\n\n## Adding This Guide in Your Repository\n\nIf you maintain a fork or your own repository and want the contribution guide to be visible and linked properly:\n\n1. **Keep `CONTRIBUTING.md` in the repository root**  \n   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.\n\n2. **Link from README**  \n   Add a short line in your main `README.md` so new contributors see it when they land on the repo, for example:\n   ```markdown\n   **Want to contribute?** See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding conventions, and the pull request process.\n   ```\n\n3. **Optional: GitHub “Contributing” link**  \n   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.\n\n4. **When forking**  \n   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.\n\n---\n\n## Reporting Bugs and Requesting Features\n\n- **Bugs**: Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md). Include version, OS, steps to reproduce, and expected vs actual behavior.\n- **Features**: Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md). Describe the use case and, if possible, a proposed approach.\n- **Questions**: Use the [question template](.github/ISSUE_TEMPLATE/question-template.md) or discussions if enabled.\n\n---\n\nThank 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.\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM --platform=$BUILDPLATFORM node:alpine AS front-builder\nWORKDIR /app\nCOPY frontend/ ./\nRUN npm install && npm run build\n\nFROM golang:1.25-alpine AS backend-builder\nWORKDIR /app\nARG TARGETARCH\nARG TARGETVARIANT\nENV CGO_ENABLED=1\nENV CGO_CFLAGS=\"-D_LARGEFILE64_SOURCE\"\nENV GOARCH=$TARGETARCH\n\nRUN apk update && apk add --no-cache \\\n    gcc \\\n    musl-dev \\\n    libc-dev \\\n    make \\\n    git \\\n    wget \\\n    unzip \\\n    bash \\\n    curl\n\nENV CC=gcc\n\nRUN CRONET_ARCH=\"$TARGETARCH\" && \\\n    CRONET_URL=\"https://github.com/SagerNet/cronet-go/releases/latest/download/libcronet-linux-${CRONET_ARCH}.so\"; \\\n    echo \"Downloading $CRONET_URL\" && \\\n    wget -q -O ./libcronet.so \"$CRONET_URL\" && \\\n    chmod 755 ./libcronet.so\n\nCOPY . .\nCOPY --from=front-builder /app/dist/ /app/web/html/\n\nRUN if [ \"$TARGETARCH\" = \"arm\" ]; then export GOARM=7; [ \"$TARGETVARIANT\" = \"v6\" ] && export GOARM=6; fi; \\\n    go build -ldflags=\"-w -s\" \\\n    -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego\" \\\n    -o sui main.go\n\nFROM alpine\nLABEL org.opencontainers.image.authors=\"alireza7@gmail.com\"\nENV TZ=Asia/Tehran\nWORKDIR /app\nRUN set -ex && apk add --no-cache --upgrade bash tzdata ca-certificates nftables\nCOPY --from=backend-builder /app/sui /app/libcronet.so /app/\nCOPY entrypoint.sh /app/\nENTRYPOINT [ \"./entrypoint.sh\" ]"
  },
  {
    "path": "Dockerfile.frontend-artifact",
    "content": "FROM golang:1.25-alpine AS backend-builder\nWORKDIR /app\nARG TARGETARCH\nARG TARGETVARIANT\nENV CGO_ENABLED=1\nENV CGO_CFLAGS=\"-D_LARGEFILE64_SOURCE\"\nENV GOARCH=$TARGETARCH\n\nRUN apk update && apk add --no-cache \\\n    gcc \\\n    musl-dev \\\n    libc-dev \\\n    make \\\n    git \\\n    wget \\\n    unzip \\\n    bash \\\n    curl\n\nENV CC=gcc\n\nRUN CRONET_ARCH=\"$TARGETARCH\" && \\\n    CRONET_URL=\"https://github.com/SagerNet/cronet-go/releases/latest/download/libcronet-linux-${CRONET_ARCH}.so\"; \\\n    echo \"Downloading $CRONET_URL\" && \\\n    wget -q -O ./libcronet.so \"$CRONET_URL\" && \\\n    chmod 755 ./libcronet.so\n\nCOPY . .\nCOPY frontend_dist/ /app/web/html/\n\nRUN if [ \"$TARGETARCH\" = \"arm\" ]; then export GOARM=7; [ \"$TARGETVARIANT\" = \"v6\" ] && export GOARM=6; fi; \\\n    go build -ldflags=\"-w -s\" \\\n    -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_purego\" \\\n    -o sui main.go\n\nFROM alpine\nLABEL org.opencontainers.image.authors=\"alireza7@gmail.com\"\nENV TZ=Asia/Tehran\nWORKDIR /app\nRUN set -ex && apk add --no-cache --upgrade bash tzdata ca-certificates nftables\nCOPY --from=backend-builder /app/sui /app/libcronet.so /app/\nCOPY entrypoint.sh /app/\nENTRYPOINT [ \"./entrypoint.sh\" ] "
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# S-UI\n**An Advanced Web Panel • Built on SagerNet/Sing-Box**\n\n![](https://img.shields.io/github/v/release/alireza0/s-ui.svg)\n![S-UI Docker pull](https://img.shields.io/docker/pulls/alireza7/s-ui.svg)\n[![Go Report Card](https://goreportcard.com/badge/github.com/alireza0/s-ui)](https://goreportcard.com/report/github.com/alireza0/s-ui)\n[![Downloads](https://img.shields.io/github/downloads/alireza0/s-ui/total.svg)](https://img.shields.io/github/downloads/alireza0/s-ui/total.svg)\n[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)\n\n> **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\n\n**If you think this project is helpful to you, you may wish to give a**:star2:\n\n**Want to contribute?** See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding conventions, testing, and the pull request process.\n\n[![\"Buy Me A Coffee\"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/alireza7)\n\n<a href=\"https://nowpayments.io/donation/alireza7\" target=\"_blank\" rel=\"noreferrer noopener\">\n   <img src=\"https://nowpayments.io/images/embeds/donation-button-white.svg\" alt=\"Crypto donation button by NOWPayments\">\n</a>\n\n## Quick Overview\n| Features                               |      Enable?       |\n| -------------------------------------- | :----------------: |\n| Multi-Protocol                         | :heavy_check_mark: |\n| Multi-Language                         | :heavy_check_mark: |\n| Multi-Client/Inbound                   | :heavy_check_mark: |\n| Advanced Traffic Routing Interface     | :heavy_check_mark: |\n| Client & Traffic & System Status       | :heavy_check_mark: |\n| Subscription Link (link/json/clash + info)| :heavy_check_mark: |\n| Dark/Light Theme                       | :heavy_check_mark: |\n| API Interface                          | :heavy_check_mark: |\n\n## Supported Platforms\n| Platform | Architecture | Status |\n|----------|--------------|---------|\n| Linux    | amd64, arm64, armv7, armv6, armv5, 386, s390x | ✅ Supported |\n| Windows  | amd64, 386, arm64 | ✅ Supported |\n| macOS    | amd64, arm64 | 🚧 Experimental |\n\n## Screenshots\n\n![\"Main\"](https://github.com/alireza0/s-ui-frontend/raw/main/media/main.png)\n\n[Other UI Screenshots](https://github.com/alireza0/s-ui-frontend/blob/main/screenshots.md)\n\n## API Documentation\n\n[API-Documentation Wiki](https://github.com/alireza0/s-ui/wiki/API-Documentation)\n\n## Default Installation Information\n- Panel Port: 2095\n- Panel Path: /app/\n- Subscription Port: 2096\n- Subscription Path: /sub/\n- User/Password: admin\n\n## Install & Upgrade to Latest Version\n\n### Linux/macOS\n```sh\nbash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/master/install.sh)\n```\n\n### Windows\n1. Download the latest Windows release from [GitHub Releases](https://github.com/alireza0/s-ui/releases/latest)\n2. Extract the ZIP file\n3. Run `install-windows.bat` as Administrator\n4. Follow the installation wizard\n\n## Install legacy Version\n\n**Step 1:** To install your desired legacy version, add the version to the end of the installation command. e.g., ver `1.0.0`:\n\n```sh\nVERSION=1.0.0 && bash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/$VERSION/install.sh) $VERSION\n```\n\n## Manual installation\n\n### Linux/macOS\n1. 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)\n2. **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)\n3. **OPTIONAL** Copy `s-ui.sh` to /usr/bin/ and run `chmod +x /usr/bin/s-ui`.\n4. Extract s-ui tar.gz file to a directory of your choice and navigate to the directory where you extracted the tar.gz file.\n5. Copy *.service files to /etc/systemd/system/ and run `systemctl daemon-reload`.\n6. Enable autostart and start S-UI service using `systemctl enable s-ui --now`\n7. Start sing-box service using `systemctl enable sing-box --now`\n\n### Windows\n1. Get the latest Windows version from GitHub: [https://github.com/alireza0/s-ui/releases/latest](https://github.com/alireza0/s-ui/releases/latest)\n2. Download the appropriate Windows package (e.g., `s-ui-windows-amd64.zip`)\n3. Extract the ZIP file to a directory of your choice\n4. Run `install-windows.bat` as Administrator\n5. Follow the installation wizard\n6. Access the panel at http://localhost:2095/app\n\n## Uninstall S-UI\n\n```sh\nsudo -i\n\nsystemctl disable s-ui  --now\n\nrm -f /etc/systemd/system/sing-box.service\nsystemctl daemon-reload\n\nrm -fr /usr/local/s-ui\nrm /usr/bin/s-ui\n```\n\n## Install using Docker\n\n<details>\n   <summary>Click for details</summary>\n\n### Usage\n\n**Step 1:** Install Docker\n\n```shell\ncurl -fsSL https://get.docker.com | sh\n```\n\n**Step 2:** Install S-UI\n\n> Docker compose method\n\n```shell\nmkdir s-ui && cd s-ui\nwget -q https://raw.githubusercontent.com/alireza0/s-ui/master/docker-compose.yml\ndocker compose up -d\n```\n\n> Use docker\n\n```shell\nmkdir s-ui && cd s-ui\ndocker run -itd \\\n    -p 2095:2095 -p 2096:2096 -p 443:443 -p 80:80 \\\n    -v $PWD/db/:/app/db/ \\\n    -v $PWD/cert/:/root/cert/ \\\n    --name s-ui --restart=unless-stopped \\\n    alireza7/s-ui:latest\n```\n\n> Build your own image\n\n```shell\ngit clone https://github.com/alireza0/s-ui\ngit submodule update --init --recursive\ndocker build -t s-ui .\n```\n\n</details>\n\n## Manual run ( contribution )\n\n<details>\n   <summary>Click for details</summary>\n\n### Build and run whole project\n```shell\n./runSUI.sh\n```\n\n### Clone the repository\n```shell\n# clone repository\ngit clone https://github.com/alireza0/s-ui\n# clone submodules\ngit submodule update --init --recursive\n```\n\n\n### - Frontend\n\nVisit [s-ui-frontend](https://github.com/alireza0/s-ui-frontend) for frontend code\n\n### - Backend\n> Please build frontend once before!\n\nTo build backend:\n```shell\n# remove old frontend compiled files\nrm -fr web/html/*\n# apply new frontend compiled files\ncp -R frontend/dist/ web/html/\n# build\ngo build -o sui main.go\n```\n\nTo run backend (from root folder of repository):\n```shell\n./sui\n```\n\n</details>\n\n## Languages\n\n- English\n- Farsi\n- Vietnamese\n- Chinese (Simplified)\n- Chinese (Traditional)\n- Russian\n\n## Features\n\n- Supported protocols:\n  - General:  Mixed, SOCKS, HTTP, HTTPS, Direct, Redirect, TProxy\n  - V2Ray based: VLESS, VMess, Trojan, Shadowsocks\n  - Other protocols: ShadowTLS, Hysteria, Hysteria2, Naive, TUIC\n- Supports XTLS protocols\n- An advanced interface for routing traffic, incorporating PROXY Protocol, External, and Transparent Proxy, SSL Certificate, and Port\n- An advanced interface for inbound and outbound configuration\n- Clients’ traffic cap and expiration date\n- Displays online clients, inbounds and outbounds with traffic statistics, and system status monitoring\n- Subscription service with ability to add external links and subscription\n- HTTPS for secure access to the web panel and subscription service (self-provided domain + SSL certificate)\n- Dark/Light theme\n\n## Environment Variables\n\n<details>\n  <summary>Click for details</summary>\n\n### Usage\n\n| Variable       |                      Type                      | Default       |\n| -------------- | :--------------------------------------------: | :------------ |\n| SUI_LOG_LEVEL  | `\"debug\"` \\| `\"info\"` \\| `\"warn\"` \\| `\"error\"` | `\"info\"`      |\n| SUI_DEBUG      |                   `boolean`                    | `false`       |\n| SUI_BIN_FOLDER |                    `string`                    | `\"bin\"`       |\n| SUI_DB_FOLDER  |                    `string`                    | `\"db\"`        |\n| SINGBOX_API    |                    `string`                    | -             |\n\n</details>\n\n## SSL Certificate\n\n<details>\n  <summary>Click for details</summary>\n\n### Certbot\n\n```bash\nsnap install core; snap refresh core\nsnap install --classic certbot\nln -s /snap/bin/certbot /usr/bin/certbot\n\ncertbot certonly --standalone --register-unsafely-without-email --non-interactive --agree-tos -d <Your Domain Name>\n```\n\n</details>\n\n## Stargazers over Time\n[![Stargazers over time](https://starchart.cc/alireza0/s-ui.svg)](https://starchart.cc/alireza0/s-ui)\n"
  },
  {
    "path": "api/apiHandler.go",
    "content": "package api\n\nimport (\n\t\"strings\"\n\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype APIHandler struct {\n\tApiService\n\tapiv2 *APIv2Handler\n}\n\nfunc NewAPIHandler(g *gin.RouterGroup, a2 *APIv2Handler) {\n\ta := &APIHandler{\n\t\tapiv2: a2,\n\t}\n\ta.initRouter(g)\n}\n\nfunc (a *APIHandler) initRouter(g *gin.RouterGroup) {\n\tg.Use(func(c *gin.Context) {\n\t\tpath := c.Request.URL.Path\n\t\tif !strings.HasSuffix(path, \"login\") && !strings.HasSuffix(path, \"logout\") {\n\t\t\tcheckLogin(c)\n\t\t}\n\t})\n\tg.POST(\"/:postAction\", a.postHandler)\n\tg.GET(\"/:getAction\", a.getHandler)\n}\n\nfunc (a *APIHandler) postHandler(c *gin.Context) {\n\tloginUser := GetLoginUser(c)\n\taction := c.Param(\"postAction\")\n\n\tswitch action {\n\tcase \"login\":\n\t\ta.ApiService.Login(c)\n\tcase \"changePass\":\n\t\ta.ApiService.ChangePass(c)\n\tcase \"save\":\n\t\ta.ApiService.Save(c, loginUser)\n\tcase \"restartApp\":\n\t\ta.ApiService.RestartApp(c)\n\tcase \"restartSb\":\n\t\ta.ApiService.RestartSb(c)\n\tcase \"linkConvert\":\n\t\ta.ApiService.LinkConvert(c)\n\tcase \"subConvert\":\n\t\ta.ApiService.SubConvert(c)\n\tcase \"importdb\":\n\t\ta.ApiService.ImportDb(c)\n\tcase \"addToken\":\n\t\ta.ApiService.AddToken(c)\n\t\ta.apiv2.ReloadTokens()\n\tcase \"deleteToken\":\n\t\ta.ApiService.DeleteToken(c)\n\t\ta.apiv2.ReloadTokens()\n\tdefault:\n\t\tjsonMsg(c, \"failed\", common.NewError(\"unknown action: \", action))\n\t}\n}\n\nfunc (a *APIHandler) getHandler(c *gin.Context) {\n\taction := c.Param(\"getAction\")\n\n\tswitch action {\n\tcase \"logout\":\n\t\ta.ApiService.Logout(c)\n\tcase \"load\":\n\t\ta.ApiService.LoadData(c)\n\tcase \"inbounds\", \"outbounds\", \"endpoints\", \"services\", \"tls\", \"clients\", \"config\":\n\t\terr := a.ApiService.LoadPartialData(c, []string{action})\n\t\tif err != nil {\n\t\t\tjsonMsg(c, action, err)\n\t\t}\n\t\treturn\n\tcase \"users\":\n\t\ta.ApiService.GetUsers(c)\n\tcase \"settings\":\n\t\ta.ApiService.GetSettings(c)\n\tcase \"stats\":\n\t\ta.ApiService.GetStats(c)\n\tcase \"status\":\n\t\ta.ApiService.GetStatus(c)\n\tcase \"onlines\":\n\t\ta.ApiService.GetOnlines(c)\n\tcase \"logs\":\n\t\ta.ApiService.GetLogs(c)\n\tcase \"changes\":\n\t\ta.ApiService.CheckChanges(c)\n\tcase \"keypairs\":\n\t\ta.ApiService.GetKeypairs(c)\n\tcase \"getdb\":\n\t\ta.ApiService.GetDb(c)\n\tcase \"tokens\":\n\t\ta.ApiService.GetTokens(c)\n\tcase \"singbox-config\":\n\t\ta.ApiService.GetSingboxConfig(c)\n\tcase \"checkOutbound\":\n\t\ta.ApiService.GetCheckOutbound(c)\n\tdefault:\n\t\tjsonMsg(c, \"failed\", common.NewError(\"unknown action: \", action))\n\t}\n}\n"
  },
  {
    "path": "api/apiService.go",
    "content": "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-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n\t\"github.com/alireza0/s-ui/util\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype ApiService struct {\n\tservice.SettingService\n\tservice.UserService\n\tservice.ConfigService\n\tservice.ClientService\n\tservice.TlsService\n\tservice.InboundService\n\tservice.OutboundService\n\tservice.EndpointService\n\tservice.ServicesService\n\tservice.PanelService\n\tservice.StatsService\n\tservice.ServerService\n}\n\nfunc (a *ApiService) LoadData(c *gin.Context) {\n\tdata, err := a.getData(c)\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tjsonObj(c, data, nil)\n}\n\nfunc (a *ApiService) getData(c *gin.Context) (interface{}, error) {\n\tdata := make(map[string]interface{}, 0)\n\tlu := c.Query(\"lu\")\n\tisUpdated, err := a.ConfigService.CheckChanges(lu)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tonlines, err := a.StatsService.GetOnlines()\n\n\tsysInfo := a.ServerService.GetSingboxInfo()\n\tif sysInfo[\"running\"] == false {\n\t\tlogs := a.ServerService.GetLogs(\"1\", \"debug\")\n\t\tif len(logs) > 0 {\n\t\t\tdata[\"lastLog\"] = logs[0]\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif isUpdated {\n\t\tconfig, err := a.SettingService.GetConfig()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tclients, err := a.ClientService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ttlsConfigs, err := a.TlsService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tinbounds, err := a.InboundService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\toutbounds, err := a.OutboundService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tendpoints, err := a.EndpointService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tservices, err := a.ServicesService.GetAll()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tsubURI, err := a.SettingService.GetFinalSubURI(getHostname(c))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ttrafficAge, err := a.SettingService.GetTrafficAge()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdata[\"config\"] = json.RawMessage(config)\n\t\tdata[\"clients\"] = clients\n\t\tdata[\"tls\"] = tlsConfigs\n\t\tdata[\"inbounds\"] = inbounds\n\t\tdata[\"outbounds\"] = outbounds\n\t\tdata[\"endpoints\"] = endpoints\n\t\tdata[\"services\"] = services\n\t\tdata[\"subURI\"] = subURI\n\t\tdata[\"enableTraffic\"] = trafficAge > 0\n\t\tdata[\"onlines\"] = onlines\n\t} else {\n\t\tdata[\"onlines\"] = onlines\n\t}\n\n\treturn data, nil\n}\n\nfunc (a *ApiService) LoadPartialData(c *gin.Context, objs []string) error {\n\tdata := make(map[string]interface{}, 0)\n\tid := c.Query(\"id\")\n\n\tfor _, obj := range objs {\n\t\tswitch obj {\n\t\tcase \"inbounds\":\n\t\t\tinbounds, err := a.InboundService.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = inbounds\n\t\tcase \"outbounds\":\n\t\t\toutbounds, err := a.OutboundService.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = outbounds\n\t\tcase \"endpoints\":\n\t\t\tendpoints, err := a.EndpointService.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = endpoints\n\t\tcase \"services\":\n\t\t\tservices, err := a.ServicesService.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = services\n\t\tcase \"tls\":\n\t\t\ttlsConfigs, err := a.TlsService.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = tlsConfigs\n\t\tcase \"clients\":\n\t\t\tclients, err := a.ClientService.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = clients\n\t\tcase \"config\":\n\t\t\tconfig, err := a.SettingService.GetConfig()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = json.RawMessage(config)\n\t\tcase \"settings\":\n\t\t\tsettings, err := a.SettingService.GetAllSetting()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata[obj] = settings\n\t\t}\n\t}\n\n\tjsonObj(c, data, nil)\n\treturn nil\n}\n\nfunc (a *ApiService) GetUsers(c *gin.Context) {\n\tusers, err := a.UserService.GetUsers()\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tjsonObj(c, *users, nil)\n}\n\nfunc (a *ApiService) GetSettings(c *gin.Context) {\n\tdata, err := a.SettingService.GetAllSetting()\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tjsonObj(c, data, err)\n}\n\nfunc (a *ApiService) GetStats(c *gin.Context) {\n\tresource := c.Query(\"resource\")\n\ttag := c.Query(\"tag\")\n\tlimit, err := strconv.Atoi(c.Query(\"limit\"))\n\tif err != nil {\n\t\tlimit = 100\n\t}\n\tdata, err := a.StatsService.GetStats(resource, tag, limit)\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tjsonObj(c, data, err)\n}\n\nfunc (a *ApiService) GetStatus(c *gin.Context) {\n\trequest := c.Query(\"r\")\n\tresult := a.ServerService.GetStatus(request)\n\tjsonObj(c, result, nil)\n}\n\nfunc (a *ApiService) GetOnlines(c *gin.Context) {\n\tonlines, err := a.StatsService.GetOnlines()\n\tjsonObj(c, onlines, err)\n}\n\nfunc (a *ApiService) GetLogs(c *gin.Context) {\n\tcount := c.Query(\"c\")\n\tlevel := c.Query(\"l\")\n\tlogs := a.ServerService.GetLogs(count, level)\n\tjsonObj(c, logs, nil)\n}\n\nfunc (a *ApiService) CheckChanges(c *gin.Context) {\n\tactor := c.Query(\"a\")\n\tchngKey := c.Query(\"k\")\n\tcount := c.Query(\"c\")\n\tchanges := a.ConfigService.GetChanges(actor, chngKey, count)\n\tjsonObj(c, changes, nil)\n}\n\nfunc (a *ApiService) GetKeypairs(c *gin.Context) {\n\tkType := c.Query(\"k\")\n\toptions := c.Query(\"o\")\n\tkeypair := a.ServerService.GenKeypair(kType, options)\n\tjsonObj(c, keypair, nil)\n}\n\nfunc (a *ApiService) GetDb(c *gin.Context) {\n\texclude := c.Query(\"exclude\")\n\tdb, err := database.GetDb(exclude)\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tc.Header(\"Content-Type\", \"application/octet-stream\")\n\tc.Header(\"Content-Disposition\", \"attachment; filename=s-ui_\"+time.Now().Format(\"20060102-150405\")+\".db\")\n\tc.Writer.Write(db)\n}\n\nfunc (a *ApiService) postActions(c *gin.Context) (string, json.RawMessage, error) {\n\tvar data map[string]json.RawMessage\n\terr := c.ShouldBind(&data)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treturn string(data[\"action\"]), data[\"data\"], nil\n}\n\nfunc (a *ApiService) Login(c *gin.Context) {\n\tremoteIP := getRemoteIp(c)\n\tloginUser, err := a.UserService.Login(c.Request.FormValue(\"user\"), c.Request.FormValue(\"pass\"), remoteIP)\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\n\tsessionMaxAge, err := a.SettingService.GetSessionMaxAge()\n\tif err != nil {\n\t\tlogger.Infof(\"Unable to get session's max age from DB\")\n\t}\n\n\terr = SetLoginUser(c, loginUser, sessionMaxAge)\n\tif err == nil {\n\t\tlogger.Info(\"user \", loginUser, \" login success\")\n\t} else {\n\t\tlogger.Warning(\"login failed: \", err)\n\t}\n\n\tjsonMsg(c, \"\", nil)\n}\n\nfunc (a *ApiService) ChangePass(c *gin.Context) {\n\tid := c.Request.FormValue(\"id\")\n\toldPass := c.Request.FormValue(\"oldPass\")\n\tnewUsername := c.Request.FormValue(\"newUsername\")\n\tnewPass := c.Request.FormValue(\"newPass\")\n\terr := a.UserService.ChangePass(id, oldPass, newUsername, newPass)\n\tif err == nil {\n\t\tlogger.Info(\"change user credentials success\")\n\t\tjsonMsg(c, \"save\", nil)\n\t} else {\n\t\tlogger.Warning(\"change user credentials failed:\", err)\n\t\tjsonMsg(c, \"\", err)\n\t}\n}\n\nfunc (a *ApiService) Save(c *gin.Context, loginUser string) {\n\thostname := getHostname(c)\n\tobj := c.Request.FormValue(\"object\")\n\tact := c.Request.FormValue(\"action\")\n\tdata := c.Request.FormValue(\"data\")\n\tinitUsers := c.Request.FormValue(\"initUsers\")\n\tobjs, err := a.ConfigService.Save(obj, act, json.RawMessage(data), initUsers, loginUser, hostname)\n\tif err != nil {\n\t\tjsonMsg(c, \"save\", err)\n\t\treturn\n\t}\n\terr = a.LoadPartialData(c, objs)\n\tif err != nil {\n\t\tjsonMsg(c, obj, err)\n\t}\n}\n\nfunc (a *ApiService) RestartApp(c *gin.Context) {\n\terr := a.PanelService.RestartPanel(3)\n\tjsonMsg(c, \"restartApp\", err)\n}\n\nfunc (a *ApiService) RestartSb(c *gin.Context) {\n\terr := a.ConfigService.RestartCore()\n\tjsonMsg(c, \"restartSb\", err)\n}\n\nfunc (a *ApiService) LinkConvert(c *gin.Context) {\n\tlink := c.Request.FormValue(\"link\")\n\tresult, _, err := util.GetOutbound(link, 0)\n\tjsonObj(c, result, err)\n}\n\nfunc (a *ApiService) SubConvert(c *gin.Context) {\n\tlink := c.Request.FormValue(\"link\")\n\tresult, err := util.GetExternalSub(link)\n\tjsonObj(c, result, err)\n}\n\nfunc (a *ApiService) ImportDb(c *gin.Context) {\n\tfile, _, err := c.Request.FormFile(\"db\")\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\terr = database.ImportDB(file)\n\tjsonMsg(c, \"\", err)\n}\n\nfunc (a *ApiService) Logout(c *gin.Context) {\n\tloginUser := GetLoginUser(c)\n\tif loginUser != \"\" {\n\t\tlogger.Infof(\"user %s logout\", loginUser)\n\t}\n\tClearSession(c)\n\tjsonMsg(c, \"\", nil)\n}\n\nfunc (a *ApiService) LoadTokens() ([]byte, error) {\n\treturn a.UserService.LoadTokens()\n}\n\nfunc (a *ApiService) GetTokens(c *gin.Context) {\n\tloginUser := GetLoginUser(c)\n\ttokens, err := a.UserService.GetUserTokens(loginUser)\n\tjsonObj(c, tokens, err)\n}\n\nfunc (a *ApiService) AddToken(c *gin.Context) {\n\tloginUser := GetLoginUser(c)\n\texpiry := c.Request.FormValue(\"expiry\")\n\texpiryInt, err := strconv.ParseInt(expiry, 10, 64)\n\tif err != nil {\n\t\tjsonMsg(c, \"\", err)\n\t\treturn\n\t}\n\tdesc := c.Request.FormValue(\"desc\")\n\ttoken, err := a.UserService.AddToken(loginUser, expiryInt, desc)\n\tjsonObj(c, token, err)\n}\n\nfunc (a *ApiService) DeleteToken(c *gin.Context) {\n\ttokenId := c.Request.FormValue(\"id\")\n\terr := a.UserService.DeleteToken(tokenId)\n\tjsonMsg(c, \"\", err)\n}\n\nfunc (a *ApiService) GetSingboxConfig(c *gin.Context) {\n\trawConfig, err := a.ConfigService.GetConfig(\"\")\n\tif err != nil {\n\t\tc.Status(400)\n\t\tc.Writer.WriteString(err.Error())\n\t\treturn\n\t}\n\tc.Header(\"Content-Type\", \"application/json\")\n\tc.Header(\"Content-Disposition\", \"attachment; filename=config_\"+time.Now().Format(\"20060102-150405\")+\".json\")\n\tc.Writer.Write(*rawConfig)\n}\n\nfunc (a *ApiService) GetCheckOutbound(c *gin.Context) {\n\ttag := c.Query(\"tag\")\n\tlink := c.Query(\"link\")\n\tresult := a.ConfigService.CheckOutbound(tag, link)\n\tjsonObj(c, result, nil)\n}\n"
  },
  {
    "path": "api/apiV2Handler.go",
    "content": "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/common\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype TokenInMemory struct {\n\tToken    string\n\tExpiry   int64\n\tUsername string\n}\n\ntype APIv2Handler struct {\n\tApiService\n\ttokens *[]TokenInMemory\n}\n\nfunc NewAPIv2Handler(g *gin.RouterGroup) *APIv2Handler {\n\ta := &APIv2Handler{}\n\ta.ReloadTokens()\n\ta.initRouter(g)\n\treturn a\n}\n\nfunc (a *APIv2Handler) initRouter(g *gin.RouterGroup) {\n\tg.Use(func(c *gin.Context) {\n\t\ta.checkToken(c)\n\t})\n\tg.POST(\"/:postAction\", a.postHandler)\n\tg.GET(\"/:getAction\", a.getHandler)\n}\n\nfunc (a *APIv2Handler) postHandler(c *gin.Context) {\n\tusername := a.findUsername(c)\n\taction := c.Param(\"postAction\")\n\n\tswitch action {\n\tcase \"save\":\n\t\ta.ApiService.Save(c, username)\n\tcase \"restartApp\":\n\t\ta.ApiService.RestartApp(c)\n\tcase \"restartSb\":\n\t\ta.ApiService.RestartSb(c)\n\tcase \"linkConvert\":\n\t\ta.ApiService.LinkConvert(c)\n\tcase \"subConvert\":\n\t\ta.ApiService.SubConvert(c)\n\tcase \"importdb\":\n\t\ta.ApiService.ImportDb(c)\n\tdefault:\n\t\tjsonMsg(c, \"failed\", common.NewError(\"unknown action: \", action))\n\t}\n}\n\nfunc (a *APIv2Handler) getHandler(c *gin.Context) {\n\taction := c.Param(\"getAction\")\n\n\tswitch action {\n\tcase \"load\":\n\t\ta.ApiService.LoadData(c)\n\tcase \"inbounds\", \"outbounds\", \"endpoints\", \"services\", \"tls\", \"clients\", \"config\":\n\t\terr := a.ApiService.LoadPartialData(c, []string{action})\n\t\tif err != nil {\n\t\t\tjsonMsg(c, action, err)\n\t\t}\n\t\treturn\n\tcase \"users\":\n\t\ta.ApiService.GetUsers(c)\n\tcase \"settings\":\n\t\ta.ApiService.GetSettings(c)\n\tcase \"stats\":\n\t\ta.ApiService.GetStats(c)\n\tcase \"status\":\n\t\ta.ApiService.GetStatus(c)\n\tcase \"onlines\":\n\t\ta.ApiService.GetOnlines(c)\n\tcase \"logs\":\n\t\ta.ApiService.GetLogs(c)\n\tcase \"changes\":\n\t\ta.ApiService.CheckChanges(c)\n\tcase \"keypairs\":\n\t\ta.ApiService.GetKeypairs(c)\n\tcase \"getdb\":\n\t\ta.ApiService.GetDb(c)\n\tcase \"checkOutbound\":\n\t\ta.ApiService.GetCheckOutbound(c)\n\tdefault:\n\t\tjsonMsg(c, \"failed\", common.NewError(\"unknown action: \", action))\n\t}\n}\n\nfunc (a *APIv2Handler) findUsername(c *gin.Context) string {\n\ttoken := c.Request.Header.Get(\"Token\")\n\tfor index, t := range *a.tokens {\n\t\tif t.Expiry > 0 && t.Expiry < time.Now().Unix() {\n\t\t\t(*a.tokens) = append((*a.tokens)[:index], (*a.tokens)[index+1:]...)\n\t\t\tcontinue\n\t\t}\n\t\tif t.Token == token {\n\t\t\treturn t.Username\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (a *APIv2Handler) checkToken(c *gin.Context) {\n\tusername := a.findUsername(c)\n\tif username != \"\" {\n\t\tc.Next()\n\t\treturn\n\t}\n\tjsonMsg(c, \"\", common.NewError(\"invalid token\"))\n\tc.Abort()\n}\n\nfunc (a *APIv2Handler) ReloadTokens() {\n\ttokens, err := a.ApiService.LoadTokens()\n\tif err == nil {\n\t\tvar newTokens []TokenInMemory\n\t\terr = json.Unmarshal(tokens, &newTokens)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"unable to load tokens: \", err)\n\t\t}\n\t\ta.tokens = &newTokens\n\t} else {\n\t\tlogger.Error(\"unable to load tokens: \", err)\n\t}\n}\n"
  },
  {
    "path": "api/session.go",
    "content": "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\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tloginUser = \"LOGIN_USER\"\n)\n\nfunc init() {\n\tgob.Register(model.User{})\n}\n\nfunc SetLoginUser(c *gin.Context, userName string, maxAge int) error {\n\toptions := sessions.Options{\n\t\tPath:   \"/\",\n\t\tSecure: false,\n\t}\n\tif maxAge > 0 {\n\t\toptions.MaxAge = maxAge * 60\n\t}\n\n\ts := sessions.Default(c)\n\ts.Set(loginUser, userName)\n\ts.Options(options)\n\n\treturn s.Save()\n}\n\nfunc SetMaxAge(c *gin.Context) error {\n\ts := sessions.Default(c)\n\ts.Options(sessions.Options{\n\t\tPath: \"/\",\n\t})\n\treturn s.Save()\n}\n\nfunc GetLoginUser(c *gin.Context) string {\n\ts := sessions.Default(c)\n\tobj := s.Get(loginUser)\n\tif obj == nil {\n\t\treturn \"\"\n\t}\n\tobjStr, ok := obj.(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn objStr\n}\n\nfunc IsLogin(c *gin.Context) bool {\n\treturn GetLoginUser(c) != \"\"\n}\n\nfunc ClearSession(c *gin.Context) {\n\ts := sessions.Default(c)\n\ts.Clear()\n\ts.Options(sessions.Options{\n\t\tPath:   \"/\",\n\t\tMaxAge: -1,\n\t})\n\ts.Save()\n}\n"
  },
  {
    "path": "api/utils.go",
    "content": "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\ntype Msg struct {\n\tSuccess bool        `json:\"success\"`\n\tMsg     string      `json:\"msg\"`\n\tObj     interface{} `json:\"obj\"`\n}\n\nfunc getRemoteIp(c *gin.Context) string {\n\tvalue := c.GetHeader(\"X-Forwarded-For\")\n\tif value != \"\" {\n\t\tips := strings.Split(value, \",\")\n\t\treturn ips[0]\n\t} else {\n\t\taddr := c.Request.RemoteAddr\n\t\tip, _, _ := net.SplitHostPort(addr)\n\t\treturn ip\n\t}\n}\n\nfunc getHostname(c *gin.Context) string {\n\thost := c.Request.Host\n\tif strings.Contains(host, \":\") {\n\t\thost, _, _ = net.SplitHostPort(c.Request.Host)\n\t\tif strings.Contains(host, \":\") {\n\t\t\thost = \"[\" + host + \"]\"\n\t\t}\n\t}\n\treturn host\n}\n\nfunc jsonMsg(c *gin.Context, msg string, err error) {\n\tjsonMsgObj(c, msg, nil, err)\n}\n\nfunc jsonObj(c *gin.Context, obj interface{}, err error) {\n\tjsonMsgObj(c, \"\", obj, err)\n}\n\nfunc jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {\n\tm := Msg{\n\t\tObj: obj,\n\t}\n\tif err == nil {\n\t\tm.Success = true\n\t\tif msg != \"\" {\n\t\t\tm.Msg = msg\n\t\t}\n\t} else {\n\t\tm.Success = false\n\t\tm.Msg = msg + \": \" + err.Error()\n\t\tlogger.Warning(\"failed :\", err)\n\t}\n\tc.JSON(http.StatusOK, m)\n}\n\nfunc pureJsonMsg(c *gin.Context, success bool, msg string) {\n\tif success {\n\t\tc.JSON(http.StatusOK, Msg{\n\t\t\tSuccess: true,\n\t\t\tMsg:     msg,\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, Msg{\n\t\t\tSuccess: false,\n\t\t\tMsg:     msg,\n\t\t})\n\t}\n}\n\nfunc checkLogin(c *gin.Context) {\n\tif !IsLogin(c) {\n\t\tif c.GetHeader(\"X-Requested-With\") == \"XMLHttpRequest\" {\n\t\t\tpureJsonMsg(c, false, \"Invalid login\")\n\t\t} else {\n\t\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login\")\n\t\t}\n\t\tc.Abort()\n\t} else {\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "app/app.go",
    "content": "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/s-ui/cronjob\"\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n\t\"github.com/alireza0/s-ui/sub\"\n\t\"github.com/alireza0/s-ui/web\"\n\n\t\"github.com/op/go-logging\"\n)\n\ntype APP struct {\n\tservice.SettingService\n\tconfigService *service.ConfigService\n\twebServer     *web.Server\n\tsubServer     *sub.Server\n\tcronJob       *cronjob.CronJob\n\tlogger        *logging.Logger\n\tcore          *core.Core\n}\n\nfunc NewApp() *APP {\n\treturn &APP{}\n}\n\nfunc (a *APP) Init() error {\n\tlog.Printf(\"%v %v\", config.GetName(), config.GetVersion())\n\n\ta.initLog()\n\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Init Setting\n\ta.SettingService.GetAllSetting()\n\n\ta.core = core.NewCore()\n\n\ta.cronJob = cronjob.NewCronJob()\n\ta.webServer = web.NewServer()\n\ta.subServer = sub.NewServer()\n\n\ta.configService = service.NewConfigService(a.core)\n\n\treturn nil\n}\n\nfunc (a *APP) Start() error {\n\tloc, err := a.SettingService.GetTimeLocation()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttrafficAge, err := a.SettingService.GetTrafficAge()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = a.cronJob.Start(loc, trafficAge)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = a.webServer.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = a.subServer.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = a.configService.StartCore()\n\tif err != nil {\n\t\tlogger.Error(err)\n\t}\n\n\treturn nil\n}\n\nfunc (a *APP) Stop() {\n\ta.cronJob.Stop()\n\terr := a.subServer.Stop()\n\tif err != nil {\n\t\tlogger.Warning(\"stop Sub Server err:\", err)\n\t}\n\terr = a.webServer.Stop()\n\tif err != nil {\n\t\tlogger.Warning(\"stop Web Server err:\", err)\n\t}\n\terr = a.configService.StopCore()\n\tif err != nil {\n\t\tlogger.Warning(\"stop Core err:\", err)\n\t}\n}\n\nfunc (a *APP) initLog() {\n\tswitch config.GetLogLevel() {\n\tcase config.Debug:\n\t\tlogger.InitLogger(logging.DEBUG)\n\tcase config.Info:\n\t\tlogger.InitLogger(logging.INFO)\n\tcase config.Warn:\n\t\tlogger.InitLogger(logging.WARNING)\n\tcase config.Error:\n\t\tlogger.InitLogger(logging.ERROR)\n\tdefault:\n\t\tlog.Fatal(\"unknown log level:\", config.GetLogLevel())\n\t}\n}\n\nfunc (a *APP) RestartApp() {\n\ta.Stop()\n\ta.Start()\n}\n\nfunc (a *APP) GetCore() *core.Core {\n\treturn a.core\n}\n"
  },
  {
    "path": "build.sh",
    "content": "#!/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/dist/* web/html/\n\nBUILD_TAGS=\"with_quic,with_grpc,with_utls,with_acme,with_gvisor,with_naive_outbound,with_musl,badlinkname,tfogo_checklinkname0\"\ngo build -ldflags '-w -s -checklinkname=0 -extldflags \"-Wl,-no_warn_duplicate_libraries\"' -tags \"$BUILD_TAGS\" -o sui main.go\n"
  },
  {
    "path": "cmd/admin.go",
    "content": "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/alireza0/s-ui/service\"\n)\n\nfunc resetAdmin() {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tuserService := service.UserService{}\n\terr = userService.UpdateFirstUser(\"admin\", \"admin\")\n\tif err != nil {\n\t\tfmt.Println(\"reset admin credentials failed:\", err)\n\t} else {\n\t\tfmt.Println(\"reset admin credentials success\")\n\t}\n}\n\nfunc updateAdmin(username string, password string) {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tif username != \"\" || password != \"\" {\n\t\tuserService := service.UserService{}\n\t\terr := userService.UpdateFirstUser(username, password)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"reset admin credentials failed:\", err)\n\t\t} else {\n\t\t\tfmt.Println(\"reset admin credentials success\")\n\t\t}\n\t}\n}\n\nfunc showAdmin() {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tuserService := service.UserService{}\n\tuserModel, err := userService.GetFirstUser()\n\tif err != nil {\n\t\tfmt.Println(\"get current user info failed,error info:\", err)\n\t}\n\tusername := userModel.Username\n\tuserpasswd := userModel.Password\n\tif (username == \"\") || (userpasswd == \"\") {\n\t\tfmt.Println(\"current username or password is empty\")\n\t}\n\tfmt.Println(\"First admin credentials:\")\n\tfmt.Println(\"\\tUsername:\\t\", username)\n\tfmt.Println(\"\\tPassword:\\t\", userpasswd)\n}\n"
  },
  {
    "path": "cmd/cmd.go",
    "content": "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/alireza0/s-ui/config\"\n)\n\nfunc ParseCmd() {\n\tvar showVersion bool\n\tflag.BoolVar(&showVersion, \"v\", false, \"show version\")\n\n\tadminCmd := flag.NewFlagSet(\"admin\", flag.ExitOnError)\n\tsettingCmd := flag.NewFlagSet(\"setting\", flag.ExitOnError)\n\n\tvar username string\n\tvar password string\n\tvar port int\n\tvar path string\n\tvar subPort int\n\tvar subPath string\n\tvar reset bool\n\tvar show bool\n\tsettingCmd.BoolVar(&reset, \"reset\", false, \"reset all settings\")\n\tsettingCmd.BoolVar(&show, \"show\", false, \"show current settings\")\n\tsettingCmd.IntVar(&port, \"port\", 0, \"set panel port\")\n\tsettingCmd.StringVar(&path, \"path\", \"\", \"set panel path\")\n\tsettingCmd.IntVar(&subPort, \"subPort\", 0, \"set sub port\")\n\tsettingCmd.StringVar(&subPath, \"subPath\", \"\", \"set sub path\")\n\n\tadminCmd.BoolVar(&show, \"show\", false, \"show first admin credentials\")\n\tadminCmd.BoolVar(&reset, \"reset\", false, \"reset first admin credentials\")\n\tadminCmd.StringVar(&username, \"username\", \"\", \"set login username\")\n\tadminCmd.StringVar(&password, \"password\", \"\", \"set login password\")\n\n\toldUsage := flag.Usage\n\tflag.Usage = func() {\n\t\toldUsage()\n\t\tfmt.Println()\n\t\tfmt.Println(\"Commands:\")\n\t\tfmt.Println(\"    admin          set/reset/show first admin credentials\")\n\t\tfmt.Println(\"    uri            Show panel URI\")\n\t\tfmt.Println(\"    migrate        migrate form older version\")\n\t\tfmt.Println(\"    setting        set/reset/show settings\")\n\t\tfmt.Println()\n\t\tadminCmd.Usage()\n\t\tfmt.Println()\n\t\tsettingCmd.Usage()\n\t}\n\n\tflag.Parse()\n\tif showVersion {\n\t\tfmt.Println(\"S-UI Panel\\t\", config.GetVersion())\n\t\tinfo, ok := debug.ReadBuildInfo()\n\t\tif ok {\n\t\t\tfor _, dep := range info.Deps {\n\t\t\t\tif dep.Path == \"github.com/sagernet/sing-box\" {\n\t\t\t\t\tfmt.Println(\"Sing-Box\\t\", dep.Version)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tswitch os.Args[1] {\n\tcase \"admin\":\n\t\terr := adminCmd.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase show:\n\t\t\tshowAdmin()\n\t\tcase reset:\n\t\t\tresetAdmin()\n\t\tdefault:\n\t\t\tupdateAdmin(username, password)\n\t\t\tshowAdmin()\n\t\t}\n\n\tcase \"uri\":\n\t\tgetPanelURI()\n\n\tcase \"migrate\":\n\t\tmigration.MigrateDb()\n\n\tcase \"setting\":\n\t\terr := settingCmd.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase show:\n\t\t\tshowSetting()\n\t\tcase reset:\n\t\t\tresetSetting()\n\t\tdefault:\n\t\t\tupdateSetting(port, path, subPort, subPath)\n\t\t\tshowSetting()\n\t\t}\n\tdefault:\n\t\tfmt.Println(\"Invalid subcommands\")\n\t\tflag.Usage()\n\t}\n}\n"
  },
  {
    "path": "cmd/migration/1_1.go",
    "content": "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/gorm\"\n)\n\nfunc migrateClientSchema(db *gorm.DB) error {\n\trows, err := db.Raw(\"PRAGMA table_info(clients)\").Rows()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tcid       int\n\t\t\tcname     string\n\t\t\tctype     string\n\t\t\tnotnull   int\n\t\t\tdfltValue interface{}\n\t\t\tpk        int\n\t\t)\n\n\t\trows.Scan(&cid, &cname, &ctype, &notnull, &dfltValue, &pk)\n\t\tif cname == \"config\" || cname == \"inbounds\" || cname == \"links\" {\n\t\t\tif ctype == \"text\" {\n\t\t\t\tfmt.Printf(\"Column %s has type TEXT\\n\", cname)\n\t\t\t\toldData := make([]struct {\n\t\t\t\t\tId   uint\n\t\t\t\t\tData string\n\t\t\t\t}, 0)\n\t\t\t\tdb.Model(model.Client{}).Select(\"id\", cname+\" as data\").Scan(&oldData)\n\t\t\t\tfor _, data := range oldData {\n\t\t\t\t\tvar newData []byte\n\t\t\t\t\tswitch cname {\n\t\t\t\t\tcase \"inbounds\":\n\t\t\t\t\t\tinbounds := strings.Split(data.Data, \",\")\n\t\t\t\t\t\tnewData, _ = json.MarshalIndent(inbounds, \"\", \"  \")\n\t\t\t\t\tcase \"config\":\n\t\t\t\t\t\tjsonData := map[string]interface{}{}\n\t\t\t\t\t\tjson.Unmarshal([]byte(data.Data), &jsonData)\n\t\t\t\t\t\tnewData, _ = json.MarshalIndent(jsonData, \"\", \"  \")\n\t\t\t\t\tcase \"links\":\n\t\t\t\t\t\tjsonData := make([]interface{}, 0)\n\t\t\t\t\t\tjson.Unmarshal([]byte(data.Data), &jsonData)\n\t\t\t\t\t\tnewData, _ = json.MarshalIndent(jsonData, \"\", \"  \")\n\t\t\t\t\t}\n\t\t\t\t\terr = db.Model(model.Client{}).Where(\"id = ?\", data.Id).UpdateColumn(cname, newData).Error\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc deleteOldWebSecret(db *gorm.DB) error {\n\treturn db.Exec(\"DELETE FROM settings WHERE key = ?\", \"webSecret\").Error\n}\n\nfunc changesObj(db *gorm.DB) error {\n\treturn db.Exec(\"UPDATE changes SET obj = CAST('\\\"' || CAST(obj AS TEXT) || '\\\"' AS BLOB) WHERE actor = ? and obj not like ?\", \"DepleteJob\", \"\\\"%\\\"\").Error\n}\n\nfunc to1_1(db *gorm.DB) error {\n\terr := migrateClientSchema(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = deleteOldWebSecret(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = changesObj(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/migration/1_2.go",
    "content": "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\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype InboundData struct {\n\tId      uint\n\tTag     string\n\tAddrs   json.RawMessage\n\tOutJson json.RawMessage\n}\n\nfunc moveJsonToDb(db *gorm.DB) error {\n\tbinFolderPath := os.Getenv(\"SUI_BIN_FOLDER\")\n\tif binFolderPath == \"\" {\n\t\tbinFolderPath = \"bin\"\n\t}\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigPath := dir + \"/\" + binFolderPath + \"/config.json\"\n\tif _, err := os.Stat(configPath); errors.Is(err, os.ErrNotExist) {\n\t\treturn nil\n\t}\n\n\tdata, err := os.ReadFile(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar oldConfig map[string]interface{}\n\terr = json.Unmarshal(data, &oldConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toldInbounds := oldConfig[\"inbounds\"].([]interface{})\n\tdb.Migrator().DropTable(&model.Inbound{})\n\tdb.AutoMigrate(&model.Inbound{})\n\tfor _, inbound := range oldInbounds {\n\t\tinbObj, _ := inbound.(map[string]interface{})\n\t\ttag, _ := inbObj[\"tag\"].(string)\n\t\tif tlsObj, ok := inbObj[\"tls\"]; ok {\n\t\t\tvar tls_id uint\n\t\t\terr = db.Raw(\"SELECT id FROM tls WHERE inbounds like ?\", `%\"`+tag+`\"%`).Find(&tls_id).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Bind or Create tls_id\n\t\t\tif tls_id > 0 {\n\t\t\t\tinbObj[\"tls_id\"] = tls_id\n\t\t\t} else {\n\t\t\t\ttls_server, _ := json.MarshalIndent(tlsObj, \"\", \"  \")\n\t\t\t\tif len(tls_server) > 5 {\n\t\t\t\t\tnewTls := &model.Tls{\n\t\t\t\t\t\tName:   tag,\n\t\t\t\t\t\tServer: tls_server,\n\t\t\t\t\t\tClient: json.RawMessage(\"{}\"),\n\t\t\t\t\t}\n\t\t\t\t\terr = db.Create(newTls).Error\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tinbObj[\"tls_id\"] = newTls.Id\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar inbData InboundData\n\t\tdb.Raw(\"select id,addrs,out_json from inbound_data where tag = ?\", tag).Find(&inbData)\n\t\tif inbData.Id > 0 {\n\t\t\tinbObj[\"out_json\"] = inbData.OutJson\n\t\t\tvar addrs []map[string]interface{}\n\t\t\tjson.Unmarshal(inbData.Addrs, &addrs)\n\t\t\tfor index, addr := range addrs {\n\t\t\t\tif tlsEnable, ok := addr[\"tls\"].(bool); ok {\n\t\t\t\t\tnewTls := map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": tlsEnable,\n\t\t\t\t\t}\n\t\t\t\t\tif insecure, ok := addr[\"insecure\"].(bool); ok {\n\t\t\t\t\t\tnewTls[\"insecure\"] = insecure\n\t\t\t\t\t\tdelete(addrs[index], \"insecure\")\n\t\t\t\t\t}\n\t\t\t\t\tif sni, ok := addr[\"server_name\"].(string); ok {\n\t\t\t\t\t\tnewTls[\"server_name\"] = sni\n\t\t\t\t\t\tdelete(addrs[index], \"server_name\")\n\t\t\t\t\t}\n\t\t\t\t\taddrs[index][\"tls\"] = newTls\n\t\t\t\t}\n\t\t\t}\n\t\t\tinbObj[\"addrs\"] = addrs\n\t\t} else {\n\t\t\tinbObj[\"out_json\"] = json.RawMessage(\"{}\")\n\t\t\tinbObj[\"addrs\"] = json.RawMessage(\"[]\")\n\t\t}\n\t\t// Delete deprecated fields\n\t\tdelete(inbObj, \"sniff\")\n\t\tdelete(inbObj, \"sniff_override_destination\")\n\t\tdelete(inbObj, \"sniff_timeout\")\n\t\tdelete(inbObj, \"domain_strategy\")\n\t\tinbJson, _ := json.Marshal(inbObj)\n\n\t\tvar newInbound model.Inbound\n\t\terr = newInbound.UnmarshalJSON(inbJson)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = db.Create(&newInbound).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdelete(oldConfig, \"inbounds\")\n\n\tblockOutboundTags := []string{}\n\tdnsOutboundTags := []string{}\n\n\toldOutbounds := oldConfig[\"outbounds\"].([]interface{})\n\tdb.Migrator().DropTable(&model.Outbound{}, &model.Endpoint{})\n\tdb.AutoMigrate(&model.Outbound{}, &model.Endpoint{})\n\tfor _, outbound := range oldOutbounds {\n\t\toutType, _ := outbound.(map[string]interface{})[\"type\"].(string)\n\t\toutboundRaw, _ := json.MarshalIndent(outbound, \"\", \"  \")\n\t\tif outType == \"wireguard\" { // Check if it is Entrypoint\n\t\t\tvar newEntrypoint model.Endpoint\n\t\t\terr = newEntrypoint.UnmarshalJSON(outboundRaw)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = db.Create(&newEntrypoint).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else { // It is Outbound\n\t\t\tvar newOutbound model.Outbound\n\t\t\terr = newOutbound.UnmarshalJSON(outboundRaw)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Delete deprecated fields\n\t\t\tif newOutbound.Type == \"direct\" {\n\t\t\t\tvar options map[string]interface{}\n\t\t\t\tjson.Unmarshal(newOutbound.Options, &options)\n\t\t\t\tdelete(options, \"override_address\")\n\t\t\t\tdelete(options, \"override_port\")\n\t\t\t\tnewOutbound.Options, _ = json.Marshal(options)\n\t\t\t}\n\n\t\t\tswitch newOutbound.Type {\n\t\t\tcase \"dns\":\n\t\t\t\tdnsOutboundTags = append(dnsOutboundTags, newOutbound.Tag)\n\t\t\tcase \"block\":\n\t\t\t\tblockOutboundTags = append(blockOutboundTags, newOutbound.Tag)\n\t\t\tdefault:\n\t\t\t\terr = db.Create(&newOutbound).Error\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete(oldConfig, \"outbounds\")\n\n\t// Check routing rules\n\tif routingRules, ok := oldConfig[\"route\"].(map[string]interface{}); ok {\n\t\tif rules, hasRules := routingRules[\"rules\"].([]interface{}); hasRules {\n\t\t\thasDns := false\n\t\t\tfor index, rule := range rules {\n\t\t\t\truleObj, _ := rule.(map[string]interface{})\n\t\t\t\tisBlock := false\n\t\t\t\tisDns := false\n\t\t\t\toutboundTag, _ := ruleObj[\"outbound\"].(string)\n\t\t\t\tfor _, tag := range blockOutboundTags {\n\t\t\t\t\tif tag == outboundTag {\n\t\t\t\t\t\tisBlock = true\n\t\t\t\t\t\tdelete(ruleObj, \"outbound\")\n\t\t\t\t\t\truleObj[\"action\"] = \"reject\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor _, tag := range dnsOutboundTags {\n\t\t\t\t\tif tag == outboundTag {\n\t\t\t\t\t\tisDns = true\n\t\t\t\t\t\thasDns = true\n\t\t\t\t\t\tdelete(ruleObj, \"outbound\")\n\t\t\t\t\t\truleObj[\"action\"] = \"hijack-dns\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isBlock && !isDns {\n\t\t\t\t\truleObj[\"action\"] = \"route\"\n\t\t\t\t}\n\t\t\t\trules[index] = ruleObj\n\t\t\t}\n\t\t\tif hasDns {\n\t\t\t\trules = append(rules, map[string]interface{}{\"action\": \"sniff\"})\n\t\t\t}\n\t\t\troutingRules[\"rules\"] = rules\n\t\t}\n\t\toldConfig[\"route\"] = routingRules\n\t}\n\n\t// Remove v2rayapi and clashapi from experimental config\n\texperimental := oldConfig[\"experimental\"].(map[string]interface{})\n\tdelete(experimental, \"v2ray_api\")\n\tdelete(experimental, \"clash_api\")\n\toldConfig[\"experimental\"] = experimental\n\n\t// Save the other configs\n\tvar otherConfigs json.RawMessage\n\totherConfigs, err = json.MarshalIndent(oldConfig, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn db.Save(&model.Setting{\n\t\tKey:   \"config\",\n\t\tValue: string(otherConfigs),\n\t}).Error\n}\n\nfunc migrateTls(db *gorm.DB) error {\n\tif !db.Migrator().HasColumn(&model.Tls{}, \"inbounds\") {\n\t\treturn nil\n\t}\n\terr := db.Migrator().DropColumn(&model.Tls{}, \"inbounds\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar tlsConfig []model.Tls\n\terr = db.Model(model.Tls{}).Scan(&tlsConfig).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor index, tls := range tlsConfig {\n\t\tvar tlsClient map[string]interface{}\n\t\terr = json.Unmarshal(tls.Client, &tlsClient)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor key := range tlsClient {\n\t\t\tswitch key {\n\t\t\tcase \"insecure\", \"disable_sni\", \"utls\", \"ech\", \"reality\":\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tdelete(tlsClient, key)\n\t\t\t}\n\t\t}\n\t\ttlsConfig[index].Client, _ = json.MarshalIndent(tlsClient, \"\", \"  \")\n\t}\n\n\treturn db.Save(&tlsConfig).Error\n}\n\nfunc dropInboundData(db *gorm.DB) error {\n\tif !db.Migrator().HasTable(&InboundData{}) {\n\t\treturn nil\n\t}\n\treturn db.Migrator().DropTable(&InboundData{})\n}\n\nfunc migrateClients(db *gorm.DB) error {\n\tvar oldClients []model.Client\n\terr := db.Model(model.Client{}).Scan(&oldClients).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor index, oldClient := range oldClients {\n\t\tvar old_inbounds []string\n\t\terr = json.Unmarshal(oldClient.Inbounds, &old_inbounds)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar inbound_ids []uint\n\t\terr = db.Raw(\"SELECT id FROM inbounds WHERE tag in ?\", old_inbounds).Find(&inbound_ids).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldClients[index].Inbounds, _ = json.Marshal(inbound_ids)\n\t}\n\treturn db.Save(oldClients).Error\n}\n\nfunc migrateChanges(db *gorm.DB) error {\n\treturn db.Migrator().DropColumn(&model.Changes{}, \"index\")\n}\n\nfunc to1_2(db *gorm.DB) error {\n\terr := moveJsonToDb(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = migrateTls(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = dropInboundData(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = migrateClients(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn migrateChanges(db)\n}\n"
  },
  {
    "path": "cmd/migration/1_3.go",
    "content": "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\"\n\n\t\"gorm.io/gorm\"\n)\n\nfunc migrate_dns(db *gorm.DB) error {\n\tvar configStr string\n\terr := db.Model(model.Setting{}).Select(\"value\").Where(\"key = ?\", \"config\").First(&configStr).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tif configStr == \"\" {\n\t\treturn nil\n\t}\n\tvar config map[string]interface{}\n\terr = json.Unmarshal([]byte(configStr), &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dnsConfig, ok := config[\"dns\"].(map[string]interface{}); ok {\n\t\tif dnsServers, ok := dnsConfig[\"servers\"].([]interface{}); ok {\n\t\t\tfor index, dnsServer := range dnsServers {\n\t\t\t\tif dnsServer, ok := dnsServer.(map[string]interface{}); ok {\n\t\t\t\t\tif addr, ok := dnsServer[\"address\"].(string); ok && addr != \"\" {\n\t\t\t\t\t\tswitch addr {\n\t\t\t\t\t\tcase \"local\":\n\t\t\t\t\t\t\tdelete(dnsServer, \"address\")\n\t\t\t\t\t\t\tdnsServer[\"type\"] = \"local\"\n\t\t\t\t\t\tcase \"fakeip\":\n\t\t\t\t\t\t\tdelete(dnsServer, \"address\")\n\t\t\t\t\t\t\tdnsServer[\"type\"] = \"fakeip\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\taddrParsed, err := url.Parse(addr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tswitch addrParsed.Scheme {\n\t\t\t\t\t\t\tcase \"\":\n\t\t\t\t\t\t\t\tdnsServer[\"type\"] = \"udp\"\n\t\t\t\t\t\t\t\tdnsServer[\"server\"] = addr\n\t\t\t\t\t\t\tcase \"udp\", \"tcp\", \"tls\", \"quic\", \"https\", \"h3\":\n\t\t\t\t\t\t\t\tdnsServer[\"type\"] = addrParsed.Scheme\n\t\t\t\t\t\t\t\tdnsServer[\"server\"] = addrParsed.Host\n\t\t\t\t\t\t\tcase \"dhcp\":\n\t\t\t\t\t\t\t\tdnsServer[\"type\"] = addrParsed.Scheme\n\t\t\t\t\t\t\t\tif addrParsed.Host != \"auto\" && addrParsed.Host != \"\" {\n\t\t\t\t\t\t\t\t\tdnsServer[\"interface\"] = addrParsed.Host\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"rcode\":\n\t\t\t\t\t\t\t\tdnsServer[\"type\"] = \"predefined\"\n\t\t\t\t\t\t\t\tdnsServer[\"responses\"] = []map[string]string{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\"rcode\": strings.ToUpper(addrParsed.Host),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdelete(dnsServer, \"address\")\n\t\t\t\t\t\t\tif addrParsed.Port() != \"\" {\n\t\t\t\t\t\t\t\tport, err := strconv.Atoi(addrParsed.Port())\n\t\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\t\tdnsServer[\"server_port\"] = port\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif address_resolver, ok := dnsServer[\"address_resolver\"].(string); ok && address_resolver != \"\" {\n\t\t\t\t\t\t\t\tdelete(dnsServer, \"address_resolver\")\n\t\t\t\t\t\t\t\tdnsServer[\"domain_resolver\"] = address_resolver\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdelete(dnsServer, \"strategy\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdnsServers[index] = dnsServer\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdnsConfig[\"servers\"] = dnsServers\n\t\t}\n\t\tconfig[\"dns\"] = dnsConfig\n\t} else {\n\t\treturn nil\n\t}\n\n\t// save changes\n\tconfigs, err := json.MarshalIndent(config, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn db.Model(model.Setting{}).Where(\"key = ?\", \"config\").Update(\"value\", string(configs)).Error\n}\n\nfunc remove_outbound_strategy(db *gorm.DB) error {\n\tvar outbounds []model.Outbound\n\terr := db.Find(&outbounds).Where(\"json_extract(options, '$.domain_strategy') IS NOT NULL\").Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, outbound := range outbounds {\n\t\tvar restFields map[string]json.RawMessage\n\t\tif err := json.Unmarshal(outbound.Options, &restFields); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(restFields, \"domain_strategy\")\n\t\toutbound.Options, _ = json.MarshalIndent(restFields, \"\", \"  \")\n\t\tdb.Save(&outbound)\n\t}\n\treturn nil\n}\n\nfunc anytls_user_config(db *gorm.DB) error {\n\tvar clients []model.Client\n\terr := db.Model(model.Client{}).Find(&clients).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor index, client := range clients {\n\t\tvar configs map[string]json.RawMessage\n\t\tif err := json.Unmarshal(client.Config, &configs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif configs[\"anytls\"] != nil {\n\t\t\tcontinue\n\t\t}\n\t\tconfigs[\"anytls\"] = configs[\"trojan\"]\n\t\tconfigJson, err := json.MarshalIndent(configs, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclients[index].Config = configJson\n\t\tdb.Save(&clients[index])\n\t}\n\treturn nil\n}\n\nfunc to1_3(db *gorm.DB) error {\n\terr := anytls_user_config(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = migrate_dns(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = remove_outbound_strategy(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/migration/main.go",
    "content": "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/gorm\"\n)\n\nfunc MigrateDb() {\n\t// void running on first install\n\tpath := config.GetDBPath()\n\t_, err := os.Stat(path)\n\tif err != nil {\n\t\tprintln(\"Database not found\")\n\t\treturn\n\t}\n\n\tdb, err := gorm.Open(sqlite.Open(path))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\ttx := db.Begin()\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\tcurrentVersion := config.GetVersion()\n\tdbVersion := \"\"\n\ttx.Raw(\"SELECT value FROM settings WHERE key = ?\", \"version\").Find(&dbVersion)\n\tfmt.Println(\"Current version:\", currentVersion, \"\\nDatabase version:\", dbVersion)\n\n\tif currentVersion == dbVersion {\n\t\tfmt.Println(\"Database is up to date, no need to migrate\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"Start migrating database...\")\n\n\t// Before 1.2\n\tif dbVersion == \"\" {\n\t\terr = to1_1(tx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Migration to 1.1 failed: \", err)\n\t\t\treturn\n\t\t}\n\t\terr = to1_2(tx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Migration to 1.2 failed: \", err)\n\t\t\treturn\n\t\t}\n\t\tdbVersion = \"1.2\"\n\t}\n\n\t// Before 1.3\n\tif dbVersion[0:3] == \"1.2\" {\n\t\terr = to1_3(tx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Migration to 1.3 failed: \", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set version\n\terr = tx.Exec(\"UPDATE settings SET value = ? WHERE key = ?\", currentVersion, \"version\").Error\n\tif err != nil {\n\t\tlog.Fatal(\"Update version failed: \", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Migration done!\")\n}\n"
  },
  {
    "path": "cmd/setting.go",
    "content": "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.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/service\"\n\n\t\"github.com/shirou/gopsutil/v4/net\"\n)\n\nfunc resetSetting() {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tsettingService := service.SettingService{}\n\terr = settingService.ResetSettings()\n\tif err != nil {\n\t\tfmt.Println(\"reset setting failed:\", err)\n\t} else {\n\t\tfmt.Println(\"reset setting success\")\n\t}\n}\n\nfunc updateSetting(port int, path string, subPort int, subPath string) {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tsettingService := service.SettingService{}\n\n\tif port > 0 {\n\t\terr := settingService.SetPort(port)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"set port failed:\", err)\n\t\t} else {\n\t\t\tfmt.Println(\"set port success\")\n\t\t}\n\t}\n\tif path != \"\" {\n\t\terr := settingService.SetWebPath(path)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"set path failed:\", err)\n\t\t} else {\n\t\t\tfmt.Println(\"set path success\")\n\t\t}\n\t}\n\tif subPort > 0 {\n\t\terr := settingService.SetSubPort(subPort)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"set sub port failed:\", err)\n\t\t} else {\n\t\t\tfmt.Println(\"set sub port success\")\n\t\t}\n\t}\n\tif subPath != \"\" {\n\t\terr := settingService.SetSubPath(subPath)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"set sub path failed:\", err)\n\t\t} else {\n\t\t\tfmt.Println(\"set sub path success\")\n\t\t}\n\t}\n}\n\nfunc showSetting() {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsettingService := service.SettingService{}\n\tallSetting, err := settingService.GetAllSetting()\n\tif err != nil {\n\t\tfmt.Println(\"get current port failed,error info:\", err)\n\t}\n\tfmt.Println(\"Current panel settings:\")\n\tfmt.Println(\"\\tPanel port:\\t\", (*allSetting)[\"webPort\"])\n\tfmt.Println(\"\\tPanel path:\\t\", (*allSetting)[\"webPath\"])\n\tif (*allSetting)[\"webListen\"] != \"\" {\n\t\tfmt.Println(\"\\tPanel IP:\\t\", (*allSetting)[\"webListen\"])\n\t}\n\tif (*allSetting)[\"webDomain\"] != \"\" {\n\t\tfmt.Println(\"\\tPanel Domain:\\t\", (*allSetting)[\"webDomain\"])\n\t}\n\tif (*allSetting)[\"webURI\"] != \"\" {\n\t\tfmt.Println(\"\\tPanel URI:\\t\", (*allSetting)[\"webURI\"])\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Current subscription settings:\")\n\tfmt.Println(\"\\tSub port:\\t\", (*allSetting)[\"subPort\"])\n\tfmt.Println(\"\\tSub path:\\t\", (*allSetting)[\"subPath\"])\n\tif (*allSetting)[\"subListen\"] != \"\" {\n\t\tfmt.Println(\"\\tSub IP:\\t\", (*allSetting)[\"subListen\"])\n\t}\n\tif (*allSetting)[\"subDomain\"] != \"\" {\n\t\tfmt.Println(\"\\tSub Domain:\\t\", (*allSetting)[\"subDomain\"])\n\t}\n\tif (*allSetting)[\"subURI\"] != \"\" {\n\t\tfmt.Println(\"\\tSub URI:\\t\", (*allSetting)[\"subURI\"])\n\t}\n}\n\nfunc getPublicIP() string {\n\tapis := []string{\n\t\t\"https://api64.ipify.org\",\n\t\t\"https://ip.sb\",\n\t\t\"https://icanhazip.com\",\n\t\t\"https://ipinfo.io/ip\",\n\t\t\"https://checkip.amazonaws.com\",\n\t}\n\ttype result struct {\n\t\tip  string\n\t\terr error\n\t}\n\tch := make(chan result, len(apis))\n\tvar wg sync.WaitGroup\n\tclient := &http.Client{Timeout: 3 * time.Second}\n\n\tfor _, api := range apis {\n\t\twg.Add(1)\n\t\tgo func(url string) {\n\t\t\tdefer wg.Done()\n\t\t\tresp, err := client.Get(url)\n\t\t\tif err != nil {\n\t\t\t\tch <- result{\"\", err}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\tch <- result{\"\", err}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- result{string(body), nil}\n\t\t}(api)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\n\tfor res := range ch {\n\t\tif res.err == nil && res.ip != \"\" {\n\t\t\treturn strings.TrimSpace(res.ip)\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc getPanelURI() {\n\terr := database.InitDB(config.GetDBPath())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsettingService := service.SettingService{}\n\tPort, _ := settingService.GetPort()\n\tBasePath, _ := settingService.GetWebPath()\n\tListen, _ := settingService.GetListen()\n\tDomain, _ := settingService.GetWebDomain()\n\tKeyFile, _ := settingService.GetKeyFile()\n\tCertFile, _ := settingService.GetCertFile()\n\tTLS := false\n\tif KeyFile != \"\" && CertFile != \"\" {\n\t\tTLS = true\n\t}\n\tProto := \"\"\n\tif TLS {\n\t\tProto = \"https://\"\n\t} else {\n\t\tProto = \"http://\"\n\t}\n\tPortText := fmt.Sprintf(\":%d\", Port)\n\tif (Port == 443 && TLS) || (Port == 80 && !TLS) {\n\t\tPortText = \"\"\n\t}\n\tif len(Domain) > 0 {\n\t\tfmt.Println(Proto + Domain + PortText + BasePath)\n\t\treturn\n\t}\n\tif len(Listen) > 0 {\n\t\tfmt.Println(Proto + Listen + PortText + BasePath)\n\t\treturn\n\t}\n\tfmt.Println(\"Local address:\")\n\tnetInterfaces, _ := net.Interfaces()\n\tfor i := 0; i < len(netInterfaces); i++ {\n\t\tif len(netInterfaces[i].Flags) > 2 && netInterfaces[i].Flags[0] == \"up\" && netInterfaces[i].Flags[1] != \"loopback\" {\n\t\t\taddrs := netInterfaces[i].Addrs\n\t\t\tfor _, address := range addrs {\n\t\t\t\tIP := strings.Split(address.Addr, \"/\")[0]\n\t\t\t\tif strings.Contains(address.Addr, \".\") {\n\t\t\t\t\tfmt.Println(Proto + IP + PortText + BasePath)\n\t\t\t\t} else if address.Addr[0:6] != \"fe80::\" {\n\t\t\t\t\tfmt.Println(Proto + \"[\" + IP + \"]\" + PortText + BasePath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpubIP := getPublicIP()\n\tif pubIP != \"\" {\n\t\tfmt.Printf(\"\\nGlobal address:\\n%s%s%s\\n\", Proto, pubIP, PortText+BasePath)\n\t}\n}\n"
  },
  {
    "path": "config/config.go",
    "content": "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 version string\n\n//go:embed name\nvar name string\n\ntype LogLevel string\n\nconst (\n\tDebug LogLevel = \"debug\"\n\tInfo  LogLevel = \"info\"\n\tWarn  LogLevel = \"warn\"\n\tError LogLevel = \"error\"\n)\n\nfunc GetVersion() string {\n\treturn strings.TrimSpace(version)\n}\n\nfunc GetName() string {\n\treturn strings.TrimSpace(name)\n}\n\nfunc GetLogLevel() LogLevel {\n\tif IsDebug() {\n\t\treturn Debug\n\t}\n\tlogLevel := os.Getenv(\"SUI_LOG_LEVEL\")\n\tif logLevel == \"\" {\n\t\treturn Info\n\t}\n\treturn LogLevel(logLevel)\n}\n\nfunc IsDebug() bool {\n\treturn os.Getenv(\"SUI_DEBUG\") == \"true\"\n}\n\nfunc GetDBFolderPath() string {\n\tdbFolderPath := os.Getenv(\"SUI_DB_FOLDER\")\n\tif dbFolderPath == \"\" {\n\t\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\t\tif err != nil {\n\t\t\t// Cross-platform fallback path\n\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\treturn \"C:\\\\Program Files\\\\s-ui\\\\db\"\n\t\t\t}\n\t\t\treturn \"/usr/local/s-ui/db\"\n\t\t}\n\t\tdbFolderPath = filepath.Join(dir, \"db\")\n\t}\n\treturn dbFolderPath\n}\n\nfunc GetDBPath() string {\n\treturn fmt.Sprintf(\"%s/%s.db\", GetDBFolderPath(), GetName())\n}\n"
  },
  {
    "path": "config/name",
    "content": "s-ui"
  },
  {
    "path": "config/version",
    "content": "1.4.0"
  },
  {
    "path": "core/box.go",
    "content": "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/sagernet/sing-box/adapter\"\n\t\"github.com/sagernet/sing-box/adapter/endpoint\"\n\t\"github.com/sagernet/sing-box/adapter/inbound\"\n\t\"github.com/sagernet/sing-box/adapter/outbound\"\n\tboxService \"github.com/sagernet/sing-box/adapter/service\"\n\t\"github.com/sagernet/sing-box/common/certificate\"\n\t\"github.com/sagernet/sing-box/common/dialer\"\n\t\"github.com/sagernet/sing-box/common/taskmonitor\"\n\tC \"github.com/sagernet/sing-box/constant\"\n\t\"github.com/sagernet/sing-box/dns\"\n\t\"github.com/sagernet/sing-box/dns/transport/local\"\n\t\"github.com/sagernet/sing-box/experimental\"\n\t\"github.com/sagernet/sing-box/experimental/cachefile\"\n\t\"github.com/sagernet/sing-box/log\"\n\t\"github.com/sagernet/sing-box/option\"\n\t\"github.com/sagernet/sing-box/protocol/direct\"\n\t\"github.com/sagernet/sing-box/route\"\n\tsbCommon \"github.com/sagernet/sing/common\"\n\tF \"github.com/sagernet/sing/common/format\"\n\t\"github.com/sagernet/sing/common/ntp\"\n\t\"github.com/sagernet/sing/service\"\n\t\"github.com/sagernet/sing/service/pause\"\n)\n\nvar _ adapter.SimpleLifecycle = (*Box)(nil)\n\ntype Box struct {\n\tcreatedAt       time.Time\n\tlogFactory      log.Factory\n\tlogger          log.ContextLogger\n\tnetwork         *route.NetworkManager\n\tendpoint        *endpoint.Manager\n\tinbound         *inbound.Manager\n\toutbound        *outbound.Manager\n\tservice         *boxService.Manager\n\tdnsTransport    *dns.TransportManager\n\tdnsRouter       *dns.Router\n\tconnection      *route.ConnectionManager\n\trouter          *route.Router\n\tinternalService []adapter.LifecycleService\n\tstatsTracker    *StatsTracker\n\tconnTracker     *ConnTracker\n\tdone            chan struct{}\n}\n\ntype Options struct {\n\toption.Options\n\tContext context.Context\n}\n\nfunc Context(\n\tctx context.Context,\n\tinboundRegistry adapter.InboundRegistry,\n\toutboundRegistry adapter.OutboundRegistry,\n\tendpointRegistry adapter.EndpointRegistry,\n\tdnsTransportRegistry adapter.DNSTransportRegistry,\n\tserviceRegistry adapter.ServiceRegistry,\n) context.Context {\n\tif service.FromContext[option.InboundOptionsRegistry](ctx) == nil ||\n\t\tservice.FromContext[adapter.InboundRegistry](ctx) == nil {\n\t\tctx = service.ContextWith[option.InboundOptionsRegistry](ctx, inboundRegistry)\n\t\tctx = service.ContextWith[adapter.InboundRegistry](ctx, inboundRegistry)\n\t}\n\tif service.FromContext[option.OutboundOptionsRegistry](ctx) == nil ||\n\t\tservice.FromContext[adapter.OutboundRegistry](ctx) == nil {\n\t\tctx = service.ContextWith[option.OutboundOptionsRegistry](ctx, outboundRegistry)\n\t\tctx = service.ContextWith[adapter.OutboundRegistry](ctx, outboundRegistry)\n\t}\n\tif service.FromContext[option.EndpointOptionsRegistry](ctx) == nil ||\n\t\tservice.FromContext[adapter.EndpointRegistry](ctx) == nil {\n\t\tctx = service.ContextWith[option.EndpointOptionsRegistry](ctx, endpointRegistry)\n\t\tctx = service.ContextWith[adapter.EndpointRegistry](ctx, endpointRegistry)\n\t}\n\tif service.FromContext[adapter.DNSTransportRegistry](ctx) == nil {\n\t\tctx = service.ContextWith[option.DNSTransportOptionsRegistry](ctx, dnsTransportRegistry)\n\t\tctx = service.ContextWith[adapter.DNSTransportRegistry](ctx, dnsTransportRegistry)\n\t}\n\tif service.FromContext[adapter.ServiceRegistry](ctx) == nil {\n\t\tctx = service.ContextWith[option.ServiceOptionsRegistry](ctx, serviceRegistry)\n\t\tctx = service.ContextWith[adapter.ServiceRegistry](ctx, serviceRegistry)\n\t}\n\treturn ctx\n}\n\nfunc NewBox(options Options) (*Box, error) {\n\tvar err error\n\tcreatedAt := time.Now()\n\tctx := options.Context\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tctx = service.ContextWithDefaultRegistry(ctx)\n\n\tendpointRegistry := service.FromContext[adapter.EndpointRegistry](ctx)\n\tinboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)\n\toutboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)\n\tdnsTransportRegistry := service.FromContext[adapter.DNSTransportRegistry](ctx)\n\tserviceRegistry := service.FromContext[adapter.ServiceRegistry](ctx)\n\n\tif endpointRegistry == nil {\n\t\treturn nil, common.NewError(\"missing endpoint registry in context\")\n\t}\n\tif inboundRegistry == nil {\n\t\treturn nil, common.NewError(\"missing inbound registry in context\")\n\t}\n\tif outboundRegistry == nil {\n\t\treturn nil, common.NewError(\"missing outbound registry in context\")\n\t}\n\tif dnsTransportRegistry == nil {\n\t\treturn nil, common.NewError(\"missing DNS transport registry in context\")\n\t}\n\tif serviceRegistry == nil {\n\t\treturn nil, common.NewError(\"missing service registry in context\")\n\t}\n\n\tctx = pause.WithDefaultManager(ctx)\n\texperimentalOptions := sbCommon.PtrValueOrDefault(options.Experimental)\n\tvar needCacheFile bool\n\tvar needClashAPI bool\n\tvar needV2RayAPI bool\n\tif experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled {\n\t\tneedCacheFile = true\n\t}\n\tif experimentalOptions.ClashAPI != nil {\n\t\tneedClashAPI = true\n\t}\n\tif experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != \"\" {\n\t\tneedV2RayAPI = true\n\t}\n\tplatformInterface := service.FromContext[adapter.PlatformInterface](ctx)\n\tvar defaultLogWriter io.Writer\n\tif platformInterface != nil {\n\t\tdefaultLogWriter = io.Discard\n\t}\n\tvar logFactory log.Factory\n\tlogFactory, err = NewFactory(log.Options{\n\t\tContext:       ctx,\n\t\tOptions:       sbCommon.PtrValueOrDefault(options.Log),\n\t\tDefaultWriter: defaultLogWriter,\n\t\tBaseTime:      createdAt,\n\t})\n\tif err != nil {\n\t\treturn nil, common.NewError(\"create log factory\", err)\n\t}\n\tfactory = logFactory\n\n\tvar internalServices []adapter.LifecycleService\n\tcertificateOptions := sbCommon.PtrValueOrDefault(options.Certificate)\n\tif C.IsAndroid || certificateOptions.Store != \"\" && certificateOptions.Store != C.CertificateStoreSystem ||\n\t\tlen(certificateOptions.Certificate) > 0 ||\n\t\tlen(certificateOptions.CertificatePath) > 0 ||\n\t\tlen(certificateOptions.CertificateDirectoryPath) > 0 {\n\t\tcertificateStore, err := certificate.NewStore(ctx, logFactory.NewLogger(\"certificate\"), certificateOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservice.MustRegister[adapter.CertificateStore](ctx, certificateStore)\n\t\tinternalServices = append(internalServices, certificateStore)\n\t}\n\n\trouteOptions := sbCommon.PtrValueOrDefault(options.Route)\n\tdnsOptions := sbCommon.PtrValueOrDefault(options.DNS)\n\tendpointManager := endpoint.NewManager(logFactory.NewLogger(\"endpoint\"), endpointRegistry)\n\tinboundManager := inbound.NewManager(logFactory.NewLogger(\"inbound\"), inboundRegistry, endpointManager)\n\toutboundManager := outbound.NewManager(logFactory.NewLogger(\"outbound\"), outboundRegistry, endpointManager, routeOptions.Final)\n\tdnsTransportManager := dns.NewTransportManager(logFactory.NewLogger(\"dns/transport\"), dnsTransportRegistry, outboundManager, dnsOptions.Final)\n\tserviceManager := boxService.NewManager(logFactory.NewLogger(\"service\"), serviceRegistry)\n\n\tservice.MustRegister[adapter.EndpointManager](ctx, endpointManager)\n\tservice.MustRegister[adapter.InboundManager](ctx, inboundManager)\n\tservice.MustRegister[adapter.OutboundManager](ctx, outboundManager)\n\tservice.MustRegister[adapter.DNSTransportManager](ctx, dnsTransportManager)\n\tservice.MustRegister[adapter.ServiceManager](ctx, serviceManager)\n\n\tdnsRouter := dns.NewRouter(ctx, logFactory, dnsOptions)\n\tservice.MustRegister[adapter.DNSRouter](ctx, dnsRouter)\n\n\tnetworkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger(\"network\"), routeOptions, dnsOptions)\n\tif err != nil {\n\t\treturn nil, common.NewError(\"initialize network manager\", err)\n\t}\n\tservice.MustRegister[adapter.NetworkManager](ctx, networkManager)\n\tconnectionManager := route.NewConnectionManager(logFactory.NewLogger(\"connection\"))\n\tservice.MustRegister[adapter.ConnectionManager](ctx, connectionManager)\n\trouter := route.NewRouter(ctx, logFactory, routeOptions, dnsOptions)\n\tservice.MustRegister[adapter.Router](ctx, router)\n\terr = router.Initialize(routeOptions.Rules, routeOptions.RuleSet)\n\tif err != nil {\n\t\treturn nil, common.NewError(\"initialize router\", err)\n\t}\n\tfor i, transportOptions := range dnsOptions.Servers {\n\t\tvar tag string\n\t\tif transportOptions.Tag != \"\" {\n\t\t\ttag = transportOptions.Tag\n\t\t} else {\n\t\t\ttag = F.ToString(i)\n\t\t}\n\t\terr = dnsTransportManager.Create(\n\t\t\tctx,\n\t\t\tlogFactory.NewLogger(F.ToString(\"dns/\", transportOptions.Type, \"[\", tag, \"]\")),\n\t\t\ttag,\n\t\t\ttransportOptions.Type,\n\t\t\ttransportOptions.Options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize DNS server[\", i, \"]\", err)\n\t\t}\n\t}\n\terr = dnsRouter.Initialize(dnsOptions.Rules)\n\tif err != nil {\n\t\treturn nil, common.NewError(\"initialize dns router\", err)\n\t}\n\tfor i, endpointOptions := range options.Endpoints {\n\t\tvar tag string\n\t\tif endpointOptions.Tag != \"\" {\n\t\t\ttag = endpointOptions.Tag\n\t\t} else {\n\t\t\ttag = F.ToString(i)\n\t\t}\n\t\terr = endpointManager.Create(\n\t\t\tctx,\n\t\t\trouter,\n\t\t\tlogFactory.NewLogger(F.ToString(\"endpoint/\", endpointOptions.Type, \"[\", tag, \"]\")),\n\t\t\ttag,\n\t\t\tendpointOptions.Type,\n\t\t\tendpointOptions.Options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize endpoint[\"+F.ToString(i)+\"] \"+tag, err)\n\t\t}\n\t}\n\tfor i, inboundOptions := range options.Inbounds {\n\t\tvar tag string\n\t\tif inboundOptions.Tag != \"\" {\n\t\t\ttag = inboundOptions.Tag\n\t\t} else {\n\t\t\ttag = F.ToString(i)\n\t\t}\n\t\terr = inboundManager.Create(\n\t\t\tctx,\n\t\t\trouter,\n\t\t\tlogFactory.NewLogger(F.ToString(\"inbound/\", inboundOptions.Type, \"[\", tag, \"]\")),\n\t\t\ttag,\n\t\t\tinboundOptions.Type,\n\t\t\tinboundOptions.Options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize inbound[\", i, \"] \", tag, err)\n\t\t}\n\t}\n\tfor i, outboundOptions := range options.Outbounds {\n\t\tvar tag string\n\t\tif outboundOptions.Tag != \"\" {\n\t\t\ttag = outboundOptions.Tag\n\t\t} else {\n\t\t\ttag = F.ToString(i)\n\t\t}\n\t\toutboundCtx := ctx\n\t\tif tag != \"\" {\n\t\t\t// TODO: remove this\n\t\t\toutboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{\n\t\t\t\tOutbound: tag,\n\t\t\t})\n\t\t}\n\t\terr = outboundManager.Create(\n\t\t\toutboundCtx,\n\t\t\trouter,\n\t\t\tlogFactory.NewLogger(F.ToString(\"outbound/\", outboundOptions.Type, \"[\", tag, \"]\")),\n\t\t\ttag,\n\t\t\toutboundOptions.Type,\n\t\t\toutboundOptions.Options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize outbound[\"+F.ToString(i)+\"] \"+tag, err)\n\t\t}\n\t}\n\tfor i, serviceOptions := range options.Services {\n\t\tvar tag string\n\t\tif serviceOptions.Tag != \"\" {\n\t\t\ttag = serviceOptions.Tag\n\t\t} else {\n\t\t\ttag = F.ToString(i)\n\t\t}\n\t\terr = serviceManager.Create(\n\t\t\tctx,\n\t\t\tlogFactory.NewLogger(F.ToString(\"service/\", serviceOptions.Type, \"[\", tag, \"]\")),\n\t\t\ttag,\n\t\t\tserviceOptions.Type,\n\t\t\tserviceOptions.Options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize service[\"+F.ToString(i)+\"]\"+tag, err)\n\t\t}\n\t}\n\toutboundManager.Initialize(func() (adapter.Outbound, error) {\n\t\treturn direct.NewOutbound(\n\t\t\tctx,\n\t\t\trouter,\n\t\t\tlogFactory.NewLogger(\"outbound/direct\"),\n\t\t\t\"direct\",\n\t\t\toption.DirectOutboundOptions{},\n\t\t)\n\t})\n\tdnsTransportManager.Initialize(func() (adapter.DNSTransport, error) {\n\t\treturn local.NewTransport(\n\t\t\tctx,\n\t\t\tlogFactory.NewLogger(\"dns/local\"),\n\t\t\t\"local\",\n\t\t\toption.LocalDNSServerOptions{},\n\t\t)\n\t})\n\tif platformInterface != nil {\n\t\terr = platformInterface.Initialize(networkManager)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(\"initialize platform interface\", err)\n\t\t}\n\t}\n\tif statsTracker == nil {\n\t\tstatsTracker = NewStatsTracker()\n\t}\n\trouter.AppendTracker(statsTracker)\n\tif connTracker == nil {\n\t\tconnTracker = NewConnTracker()\n\t}\n\trouter.AppendTracker(connTracker)\n\n\tif needCacheFile {\n\t\tcacheFile := cachefile.New(ctx, sbCommon.PtrValueOrDefault(experimentalOptions.CacheFile))\n\t\tservice.MustRegister[adapter.CacheFile](ctx, cacheFile)\n\t\tinternalServices = append(internalServices, cacheFile)\n\t}\n\tif needClashAPI {\n\t\tclashAPIOptions := sbCommon.PtrValueOrDefault(experimentalOptions.ClashAPI)\n\t\tclashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)\n\t\tclashServer, err := experimental.NewClashServer(ctx, logFactory.(log.ObservableFactory), clashAPIOptions)\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(err, \"create clash-server\")\n\t\t}\n\t\trouter.AppendTracker(clashServer)\n\t\tservice.MustRegister[adapter.ClashServer](ctx, clashServer)\n\t\tinternalServices = append(internalServices, clashServer)\n\t}\n\tif needV2RayAPI {\n\t\tv2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger(\"v2ray-api\"), sbCommon.PtrValueOrDefault(experimentalOptions.V2RayAPI))\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(err, \"create v2ray-server\")\n\t\t}\n\t\tif v2rayServer.StatsService() != nil {\n\t\t\trouter.AppendTracker(v2rayServer.StatsService())\n\t\t\tinternalServices = append(internalServices, v2rayServer)\n\t\t\tservice.MustRegister[adapter.V2RayServer](ctx, v2rayServer)\n\t\t}\n\t}\n\tntpOptions := sbCommon.PtrValueOrDefault(options.NTP)\n\tif ntpOptions.Enabled {\n\t\tntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions, ntpOptions.ServerIsDomain())\n\t\tif err != nil {\n\t\t\treturn nil, common.NewError(err, \"create NTP service\")\n\t\t}\n\t\ttimeService := ntp.NewService(ntp.Options{\n\t\t\tContext:       ctx,\n\t\t\tDialer:        ntpDialer,\n\t\t\tLogger:        logFactory.NewLogger(\"ntp\"),\n\t\t\tServer:        ntpOptions.ServerOptions.Build(),\n\t\t\tInterval:      time.Duration(ntpOptions.Interval),\n\t\t\tWriteToSystem: ntpOptions.WriteToSystem,\n\t\t})\n\t\tservice.MustRegister[ntp.TimeService](ctx, timeService)\n\t\tinternalServices = append(internalServices, adapter.NewLifecycleService(timeService, \"ntp service\"))\n\t}\n\treturn &Box{\n\t\tnetwork:         networkManager,\n\t\tendpoint:        endpointManager,\n\t\tinbound:         inboundManager,\n\t\toutbound:        outboundManager,\n\t\tdnsTransport:    dnsTransportManager,\n\t\tservice:         serviceManager,\n\t\tdnsRouter:       dnsRouter,\n\t\tconnection:      connectionManager,\n\t\trouter:          router,\n\t\tcreatedAt:       createdAt,\n\t\tlogFactory:      logFactory,\n\t\tlogger:          logFactory.Logger(),\n\t\tinternalService: internalServices,\n\t\tstatsTracker:    statsTracker,\n\t\tconnTracker:     connTracker,\n\t\tdone:            make(chan struct{}),\n\t}, nil\n}\n\nfunc (s *Box) PreStart() error {\n\terr := s.preStart()\n\tif err != nil {\n\t\t// TODO: remove catch error\n\t\tdefer func() {\n\t\t\tv := recover()\n\t\t\tif v != nil {\n\t\t\t\ts.logger.Error(err.Error())\n\t\t\t\ts.logger.Error(\"panic on early close: \" + fmt.Sprint(v))\n\t\t\t}\n\t\t}()\n\t\ts.Close()\n\t\treturn err\n\t}\n\ts.logger.Info(\"sing-box pre-started (\", F.Seconds(time.Since(s.createdAt).Seconds()), \"s)\")\n\treturn nil\n}\n\nfunc (s *Box) Start() error {\n\terr := s.start()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(\"sing-box started (\", F.Seconds(time.Since(s.createdAt).Seconds()), \"s)\")\n\treturn nil\n}\n\nfunc (s *Box) preStart() error {\n\tmonitor := taskmonitor.New(s.logger, C.StartTimeout)\n\tmonitor.Start(\"start logger\")\n\terr := s.logFactory.Start()\n\tmonitor.Finish()\n\tif err != nil {\n\t\treturn common.NewError(err, \"start logger\")\n\t}\n\terr = adapter.StartNamed(s.logger, adapter.StartStateInitialize, s.internalService) // cache-file clash-api v2ray-api\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.Start(s.logger, adapter.StartStateInitialize, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint, s.service)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.Start(s.logger, adapter.StartStateStart, s.outbound, s.dnsTransport, s.dnsRouter, s.network, s.connection, s.router)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Box) start() error {\n\terr := s.preStart()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.StartNamed(s.logger, adapter.StartStateStart, s.internalService)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.Start(s.logger, adapter.StartStateStart, s.inbound, s.endpoint, s.service)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.Start(s.logger, adapter.StartStatePostStart, s.outbound, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.inbound, s.endpoint, s.service)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.StartNamed(s.logger, adapter.StartStatePostStart, s.internalService)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.Start(s.logger, adapter.StartStateStarted, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint, s.service)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = adapter.StartNamed(s.logger, adapter.StartStateStarted, s.internalService)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Box) Close() error {\n\tselect {\n\tcase <-s.done:\n\t\treturn nil\n\tdefault:\n\t\tclose(s.done)\n\t}\n\tvar err error\n\ts.logger.Info(\"closing sing-box\")\n\tfor _, closeItem := range []struct {\n\t\tname    string\n\t\tservice adapter.Lifecycle\n\t}{\n\t\t{\"service\", s.service},\n\t\t{\"endpoint\", s.endpoint},\n\t\t{\"inbound\", s.inbound},\n\t\t{\"outbound\", s.outbound},\n\t\t{\"router\", s.router},\n\t\t{\"connection\", s.connection},\n\t\t{\"dns-router\", s.dnsRouter},\n\t\t{\"dns-transport\", s.dnsTransport},\n\t\t{\"network\", s.network},\n\t} {\n\t\tif closeItem.service == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif v := recover(); v != nil {\n\t\t\t\t\terr = errors.Join(err, common.NewError(fmt.Errorf(\"panic: %v\", v), \"close \"+closeItem.name))\n\t\t\t\t\ts.logger.Error(\"panic closing \", closeItem.name, \": \", v)\n\t\t\t\t}\n\t\t\t}()\n\t\t\ts.logger.Trace(\"close \", closeItem.name)\n\t\t\tstartTime := time.Now()\n\t\t\tcloseErr := closeItem.service.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\tcloseErr = common.NewError(closeErr, \"close \"+closeItem.name)\n\t\t\t}\n\t\t\terr = errors.Join(err, closeErr)\n\t\t\ts.logger.Trace(\"close \", closeItem.name, \" completed (\", F.Seconds(time.Since(startTime).Seconds()), \"s)\")\n\t\t}()\n\t}\n\tfor _, lifecycleService := range s.internalService {\n\t\tif lifecycleService == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif v := recover(); v != nil {\n\t\t\t\t\terr = errors.Join(err, common.NewError(fmt.Errorf(\"panic: %v\", v), \"close \"+lifecycleService.Name()))\n\t\t\t\t\ts.logger.Error(\"panic closing \", lifecycleService.Name(), \": \", v)\n\t\t\t\t}\n\t\t\t}()\n\t\t\ts.logger.Trace(\"close \", lifecycleService.Name())\n\t\t\tstartTime := time.Now()\n\t\t\tcloseErr := lifecycleService.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\tcloseErr = common.NewError(closeErr, \"close \"+lifecycleService.Name())\n\t\t\t}\n\t\t\terr = errors.Join(err, closeErr)\n\t\t\ts.logger.Trace(\"close \", lifecycleService.Name(), \" completed (\", F.Seconds(time.Since(startTime).Seconds()), \"s)\")\n\t\t}()\n\t}\n\ts.logger.Trace(\"close logger\")\n\tstartTime := time.Now()\n\tcloseErr := s.logFactory.Close()\n\tif closeErr != nil {\n\t\tcloseErr = common.NewError(closeErr, \"close logger\")\n\t}\n\terr = errors.Join(err, closeErr)\n\ts.logger.Trace(\"close logger completed (\", F.Seconds(time.Since(startTime).Seconds()), \"s)\")\n\ts.logger.Info(\"sing-box closed (live time: \", F.Seconds(time.Since(s.createdAt).Seconds()), \"s)\")\n\treturn err\n}\n\nfunc (s *Box) Uptime() uint32 {\n\treturn uint32(time.Now().Sub(s.createdAt).Seconds())\n}\n\nfunc (s *Box) Network() adapter.NetworkManager {\n\treturn s.network\n}\n\nfunc (s *Box) Router() adapter.Router {\n\treturn s.router\n}\n\nfunc (s *Box) Inbound() adapter.InboundManager {\n\treturn s.inbound\n}\n\nfunc (s *Box) Outbound() adapter.OutboundManager {\n\treturn s.outbound\n}\n\nfunc (s *Box) Endpoint() adapter.EndpointManager {\n\treturn s.endpoint\n}\n\nfunc (s *Box) StatsTracker() *StatsTracker {\n\treturn s.statsTracker\n}\n\nfunc (s *Box) ConnTracker() *ConnTracker {\n\treturn s.connTracker\n}\n"
  },
  {
    "path": "core/endpoint.go",
    "content": "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/sing-box/adapter\"\n\t\"github.com/sagernet/sing-box/option\"\n)\n\nfunc (c *Core) AddInbound(config []byte) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tvar err error\n\tvar inbound_config option.Inbound\n\terr = inbound_config.UnmarshalJSONContext(c.GetCtx(), config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = inbound_manager.Create(\n\t\tc.GetCtx(),\n\t\trouter,\n\t\tfactory.NewLogger(\"inbound/\"+inbound_config.Type+\"[\"+inbound_config.Tag+\"]\"),\n\t\tinbound_config.Tag,\n\t\tinbound_config.Type,\n\t\tinbound_config.Options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *Core) RemoveInbound(tag string) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tlogger.Info(\"remove inbound: \", tag)\n\treturn inbound_manager.Remove(tag)\n}\n\nfunc (c *Core) AddOutbound(config []byte) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tvar err error\n\tvar outbound_config option.Outbound\n\n\terr = outbound_config.UnmarshalJSONContext(c.GetCtx(), config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutboundCtx := adapter.WithContext(c.GetCtx(), &adapter.InboundContext{\n\t\tOutbound: outbound_config.Tag,\n\t})\n\n\terr = outbound_manager.Create(\n\t\toutboundCtx,\n\t\trouter,\n\t\tfactory.NewLogger(\"outbound/\"+outbound_config.Type+\"[\"+outbound_config.Tag+\"]\"),\n\t\toutbound_config.Tag,\n\t\toutbound_config.Type,\n\t\toutbound_config.Options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *Core) RemoveOutbound(tag string) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tlogger.Info(\"remove outbound: \", tag)\n\treturn outbound_manager.Remove(tag)\n}\n\nfunc (c *Core) AddEndpoint(config []byte) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tvar err error\n\tvar endpoint_config option.Endpoint\n\n\terr = endpoint_config.UnmarshalJSONContext(c.GetCtx(), config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = endpoint_manager.Create(\n\t\tc.GetCtx(),\n\t\trouter,\n\t\tfactory.NewLogger(\"endpoint/\"+endpoint_config.Type+\"[\"+endpoint_config.Tag+\"]\"),\n\t\tendpoint_config.Tag,\n\t\tendpoint_config.Type,\n\t\tendpoint_config.Options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *Core) RemoveEndpoint(tag string) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tlogger.Info(\"remove endpoint: \", tag)\n\treturn endpoint_manager.Remove(tag)\n}\n\nfunc (c *Core) AddService(config []byte) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tvar err error\n\tvar srv_config option.Service\n\n\terr = srv_config.UnmarshalJSONContext(c.GetCtx(), config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = service_manager.Create(\n\t\tc.GetCtx(),\n\t\tfactory.NewLogger(\"service/\"+srv_config.Type+\"[\"+srv_config.Tag+\"]\"),\n\t\tsrv_config.Tag,\n\t\tsrv_config.Type,\n\t\tsrv_config.Options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *Core) RemoveService(tag string) error {\n\tif !c.isRunning {\n\t\treturn common.NewError(\"sing-box is not running\")\n\t}\n\tlogger.Info(\"remove service: \", tag)\n\treturn service_manager.Remove(tag)\n}\n"
  },
  {
    "path": "core/log.go",
    "content": "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/sing-box/log\"\n\t\"github.com/sagernet/sing/common\"\n\tF \"github.com/sagernet/sing/common/format\"\n\t\"github.com/sagernet/sing/common/observable\"\n\t\"github.com/sagernet/sing/service/filemanager\"\n)\n\ntype PlatformWriter struct{}\n\nfunc (p PlatformWriter) DisableColors() bool {\n\treturn true\n}\nfunc (p PlatformWriter) WriteMessage(level log.Level, message string) {\n\tswitch level {\n\tcase log.LevelInfo:\n\t\tsuiLog.Info(message)\n\tcase log.LevelWarn:\n\t\tsuiLog.Warning(message)\n\tcase log.LevelPanic:\n\tcase log.LevelFatal:\n\tcase log.LevelError:\n\t\tsuiLog.Error(message)\n\tdefault:\n\t\tsuiLog.Debug(message)\n\t}\n}\n\nfunc NewFactory(options log.Options) (log.Factory, error) {\n\tlogOptions := options.Options\n\n\tif logOptions.Disabled {\n\t\treturn log.NewNOPFactory(), nil\n\t}\n\n\tvar logWriter io.Writer\n\tvar logFilePath string\n\n\tswitch logOptions.Output {\n\tcase \"\":\n\t\tlogWriter = options.DefaultWriter\n\t\tif logWriter == nil {\n\t\t\tlogWriter = os.Stderr\n\t\t}\n\tcase \"stderr\":\n\t\tlogWriter = os.Stderr\n\tcase \"stdout\":\n\t\tlogWriter = os.Stdout\n\tdefault:\n\t\tlogFilePath = logOptions.Output\n\t}\n\tlogFormatter := log.Formatter{\n\t\tBaseTime:         options.BaseTime,\n\t\tDisableColors:    logOptions.DisableColor || logFilePath != \"\",\n\t\tDisableTimestamp: !logOptions.Timestamp && logFilePath != \"\",\n\t\tFullTimestamp:    logOptions.Timestamp,\n\t\tTimestampFormat:  \"-0700 2006-01-02 15:04:05\",\n\t}\n\tfactory := NewDefaultFactory(\n\t\toptions.Context,\n\t\tlogFormatter,\n\t\tlogWriter,\n\t\tlogFilePath,\n\t)\n\tif logOptions.Level != \"\" {\n\t\tlogLevel, err := log.ParseLevel(logOptions.Level)\n\t\tif err != nil {\n\t\t\treturn nil, common.Error(\"parse log level\", err)\n\t\t}\n\t\tfactory.SetLevel(logLevel)\n\t} else {\n\t\tfactory.SetLevel(log.LevelTrace)\n\t}\n\treturn factory, nil\n}\n\nvar _ log.Factory = (*defaultFactory)(nil)\n\ntype defaultFactory struct {\n\tctx        context.Context\n\tformatter  log.Formatter\n\twriter     io.Writer\n\tfile       *os.File\n\tfilePath   string\n\tlevel      log.Level\n\tsubscriber *observable.Subscriber[log.Entry]\n\tobserver   *observable.Observer[log.Entry]\n}\n\nfunc NewDefaultFactory(\n\tctx context.Context,\n\tformatter log.Formatter,\n\twriter io.Writer,\n\tfilePath string,\n) log.ObservableFactory {\n\tfactory := &defaultFactory{\n\t\tctx:        ctx,\n\t\tformatter:  formatter,\n\t\twriter:     writer,\n\t\tfilePath:   filePath,\n\t\tlevel:      log.LevelTrace,\n\t\tsubscriber: observable.NewSubscriber[log.Entry](128),\n\t}\n\treturn factory\n}\n\nfunc (f *defaultFactory) Start() error {\n\tif f.filePath != \"\" {\n\t\tlogFile, err := filemanager.OpenFile(f.ctx, f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.writer = logFile\n\t\tf.file = logFile\n\t}\n\treturn nil\n}\n\nfunc (f *defaultFactory) Close() error {\n\treturn common.Close(\n\t\tcommon.PtrOrNil(f.file),\n\t\tf.subscriber,\n\t)\n}\n\nfunc (f *defaultFactory) Level() log.Level {\n\treturn f.level\n}\n\nfunc (f *defaultFactory) SetLevel(level log.Level) {\n\tf.level = level\n}\n\nfunc (f *defaultFactory) Logger() log.ContextLogger {\n\treturn f.NewLogger(\"\")\n}\n\nfunc (f *defaultFactory) NewLogger(tag string) log.ContextLogger {\n\treturn &observableLogger{f, tag}\n}\n\nfunc (f *defaultFactory) Subscribe() (subscription observable.Subscription[log.Entry], done <-chan struct{}, err error) {\n\treturn f.observer.Subscribe()\n}\n\nfunc (f *defaultFactory) UnSubscribe(sub observable.Subscription[log.Entry]) {\n\tf.observer.UnSubscribe(sub)\n}\n\ntype observableLogger struct {\n\t*defaultFactory\n\ttag string\n}\n\nfunc (l *observableLogger) Log(ctx context.Context, level log.Level, args []any) {\n\tlevel = log.OverrideLevelFromContext(level, ctx)\n\tif level > l.level {\n\t\treturn\n\t}\n\tmsg := F.ToString(args...)\n\tswitch level {\n\tcase log.LevelInfo:\n\t\tsuiLog.Info(l.tag, msg)\n\tcase log.LevelWarn:\n\t\tsuiLog.Warning(l.tag, msg)\n\tcase log.LevelPanic:\n\tcase log.LevelFatal:\n\tcase log.LevelError:\n\t\tsuiLog.Error(l.tag, msg)\n\tdefault:\n\t\tsuiLog.Debug(l.tag, msg)\n\t}\n\tif (l.filePath != \"\" || l.writer != os.Stderr) && l.writer != nil {\n\t\tmessage := l.formatter.Format(ctx, level, l.tag, msg, time.Now())\n\t\tl.writer.Write([]byte(message))\n\t}\n}\n\nfunc (l *observableLogger) Trace(args ...any) {\n\tl.TraceContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Debug(args ...any) {\n\tl.DebugContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Info(args ...any) {\n\tl.InfoContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Warn(args ...any) {\n\tl.WarnContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Error(args ...any) {\n\tl.ErrorContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Fatal(args ...any) {\n\tl.FatalContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) Panic(args ...any) {\n\tl.PanicContext(context.Background(), args...)\n}\n\nfunc (l *observableLogger) TraceContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelTrace, args)\n}\n\nfunc (l *observableLogger) DebugContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelDebug, args)\n}\n\nfunc (l *observableLogger) InfoContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelInfo, args)\n}\n\nfunc (l *observableLogger) WarnContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelWarn, args)\n}\n\nfunc (l *observableLogger) ErrorContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelError, args)\n}\n\nfunc (l *observableLogger) FatalContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelFatal, args)\n}\n\nfunc (l *observableLogger) PanicContext(ctx context.Context, args ...any) {\n\tl.Log(ctx, log.LevelPanic, args)\n}\n"
  },
  {
    "path": "core/main.go",
    "content": "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/sagernet/sing-box/adapter\"\n\t_ \"github.com/sagernet/sing-box/experimental/clashapi\"\n\t_ \"github.com/sagernet/sing-box/experimental/v2rayapi\"\n\t\"github.com/sagernet/sing-box/log\"\n\t\"github.com/sagernet/sing-box/option\"\n\t_ \"github.com/sagernet/sing-box/transport/v2rayquic\"\n\t\"github.com/sagernet/sing/service\"\n)\n\nvar (\n\tglobalCtx        context.Context\n\tinbound_manager  adapter.InboundManager\n\toutbound_manager adapter.OutboundManager\n\tservice_manager  adapter.ServiceManager\n\tendpoint_manager adapter.EndpointManager\n\trouter           adapter.Router\n\tstatsTracker     *StatsTracker\n\tconnTracker      *ConnTracker\n\tfactory          log.Factory\n)\n\ntype Core struct {\n\tisRunning bool\n\tinstance  *Box\n}\n\nfunc NewCore() *Core {\n\tglobalCtx = context.Background()\n\tglobalCtx = sb.Context(globalCtx, InboundRegistry(), OutboundRegistry(), EndpointRegistry(), DNSTransportRegistry(), ServiceRegistry())\n\treturn &Core{\n\t\tisRunning: false,\n\t\tinstance:  nil,\n\t}\n}\n\nfunc (c *Core) GetCtx() context.Context {\n\treturn globalCtx\n}\n\nfunc (c *Core) GetInstance() *Box {\n\treturn c.instance\n}\n\nfunc (c *Core) Start(sbConfig []byte) error {\n\tvar opt option.Options\n\terr := opt.UnmarshalJSONContext(globalCtx, sbConfig)\n\tif err != nil {\n\t\tlogger.Error(\"Unmarshal config err:\", err.Error())\n\t}\n\n\tc.instance, err = NewBox(Options{\n\t\tContext: globalCtx,\n\t\tOptions: opt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.instance.Start()\n\tif err != nil {\n\t\t_ = c.instance.Close()\n\t\tc.instance = nil\n\t\treturn err\n\t}\n\n\tglobalCtx = service.ContextWith(globalCtx, c)\n\tinbound_manager = service.FromContext[adapter.InboundManager](globalCtx)\n\toutbound_manager = service.FromContext[adapter.OutboundManager](globalCtx)\n\tservice_manager = service.FromContext[adapter.ServiceManager](globalCtx)\n\tendpoint_manager = service.FromContext[adapter.EndpointManager](globalCtx)\n\trouter = service.FromContext[adapter.Router](globalCtx)\n\n\tc.isRunning = true\n\treturn nil\n}\n\nfunc (c *Core) Stop() error {\n\tc.isRunning = false\n\tif c.instance == nil {\n\t\treturn nil\n\t}\n\terr := c.instance.Close()\n\tc.instance = nil\n\treturn err\n}\n\nfunc (c *Core) IsRunning() bool {\n\treturn c.isRunning\n}\n"
  },
  {
    "path": "core/outbound_check.go",
    "content": "package core\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\turltest \"github.com/sagernet/sing-box/common/urltest\"\n)\n\nconst checkTimeout = 15 * time.Second\n\ntype CheckOutboundResult struct {\n\tOK    bool\n\tDelay uint16\n\tError string\n}\n\nfunc CheckOutbound(ctx context.Context, tag string, link string) (result CheckOutboundResult) {\n\tif outbound_manager == nil {\n\t\tresult.Error = \"core not running\"\n\t\treturn result\n\t}\n\tob, ok := outbound_manager.Outbound(tag)\n\tif !ok {\n\t\tresult.Error = \"outbound not found\"\n\t\treturn result\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, checkTimeout)\n\tdefer cancel()\n\n\tdelay, err := urltest.URLTest(ctx, link, ob)\n\tif err != nil {\n\t\tresult.Error = err.Error()\n\t\treturn result\n\t}\n\tresult.OK = true\n\tresult.Delay = delay\n\treturn result\n}\n"
  },
  {
    "path": "core/register.go",
    "content": "package core\n\nimport (\n\t\"github.com/sagernet/sing-box/adapter/endpoint\"\n\t\"github.com/sagernet/sing-box/adapter/inbound\"\n\t\"github.com/sagernet/sing-box/adapter/outbound\"\n\t\"github.com/sagernet/sing-box/adapter/service\"\n\t\"github.com/sagernet/sing-box/dns\"\n\t\"github.com/sagernet/sing-box/dns/transport\"\n\t\"github.com/sagernet/sing-box/dns/transport/dhcp\"\n\t\"github.com/sagernet/sing-box/dns/transport/fakeip\"\n\t\"github.com/sagernet/sing-box/dns/transport/hosts\"\n\t\"github.com/sagernet/sing-box/dns/transport/local\"\n\t\"github.com/sagernet/sing-box/dns/transport/quic\"\n\t\"github.com/sagernet/sing-box/protocol/anytls\"\n\t\"github.com/sagernet/sing-box/protocol/block\"\n\t\"github.com/sagernet/sing-box/protocol/direct\"\n\t\"github.com/sagernet/sing-box/protocol/group\"\n\t\"github.com/sagernet/sing-box/protocol/http\"\n\t\"github.com/sagernet/sing-box/protocol/hysteria\"\n\t\"github.com/sagernet/sing-box/protocol/hysteria2\"\n\t\"github.com/sagernet/sing-box/protocol/mixed\"\n\t\"github.com/sagernet/sing-box/protocol/naive\"\n\t_ \"github.com/sagernet/sing-box/protocol/naive/quic\"\n\t\"github.com/sagernet/sing-box/protocol/redirect\"\n\t\"github.com/sagernet/sing-box/protocol/shadowsocks\"\n\t\"github.com/sagernet/sing-box/protocol/shadowtls\"\n\t\"github.com/sagernet/sing-box/protocol/socks\"\n\t\"github.com/sagernet/sing-box/protocol/ssh\"\n\t\"github.com/sagernet/sing-box/protocol/tailscale\"\n\t\"github.com/sagernet/sing-box/protocol/tor\"\n\t\"github.com/sagernet/sing-box/protocol/trojan\"\n\t\"github.com/sagernet/sing-box/protocol/tuic\"\n\t\"github.com/sagernet/sing-box/protocol/tun\"\n\t\"github.com/sagernet/sing-box/protocol/vless\"\n\t\"github.com/sagernet/sing-box/protocol/vmess\"\n\t\"github.com/sagernet/sing-box/protocol/wireguard\"\n\t\"github.com/sagernet/sing-box/service/ccm\"\n\t\"github.com/sagernet/sing-box/service/derp\"\n\t\"github.com/sagernet/sing-box/service/ocm\"\n\t\"github.com/sagernet/sing-box/service/resolved\"\n\t\"github.com/sagernet/sing-box/service/ssmapi\"\n\t_ \"github.com/sagernet/sing-box/transport/v2rayquic\"\n)\n\nfunc InboundRegistry() *inbound.Registry {\n\tregistry := inbound.NewRegistry()\n\n\ttun.RegisterInbound(registry)\n\tredirect.RegisterRedirect(registry)\n\tredirect.RegisterTProxy(registry)\n\tdirect.RegisterInbound(registry)\n\n\tsocks.RegisterInbound(registry)\n\thttp.RegisterInbound(registry)\n\tmixed.RegisterInbound(registry)\n\n\tshadowsocks.RegisterInbound(registry)\n\tvmess.RegisterInbound(registry)\n\ttrojan.RegisterInbound(registry)\n\tnaive.RegisterInbound(registry)\n\tshadowtls.RegisterInbound(registry)\n\tvless.RegisterInbound(registry)\n\tanytls.RegisterInbound(registry)\n\n\thysteria.RegisterInbound(registry)\n\ttuic.RegisterInbound(registry)\n\thysteria2.RegisterInbound(registry)\n\n\treturn registry\n}\n\nfunc OutboundRegistry() *outbound.Registry {\n\tregistry := outbound.NewRegistry()\n\n\tdirect.RegisterOutbound(registry)\n\n\tblock.RegisterOutbound(registry)\n\n\tgroup.RegisterSelector(registry)\n\tgroup.RegisterURLTest(registry)\n\n\tsocks.RegisterOutbound(registry)\n\thttp.RegisterOutbound(registry)\n\tshadowsocks.RegisterOutbound(registry)\n\tvmess.RegisterOutbound(registry)\n\ttrojan.RegisterOutbound(registry)\n\tregisterNaiveOutbound(registry)\n\ttor.RegisterOutbound(registry)\n\tssh.RegisterOutbound(registry)\n\tshadowtls.RegisterOutbound(registry)\n\tvless.RegisterOutbound(registry)\n\tanytls.RegisterOutbound(registry)\n\n\thysteria.RegisterOutbound(registry)\n\ttuic.RegisterOutbound(registry)\n\thysteria2.RegisterOutbound(registry)\n\n\treturn registry\n}\n\nfunc EndpointRegistry() *endpoint.Registry {\n\tregistry := endpoint.NewRegistry()\n\n\twireguard.RegisterEndpoint(registry)\n\ttailscale.RegisterEndpoint(registry)\n\n\treturn registry\n}\n\nfunc DNSTransportRegistry() *dns.TransportRegistry {\n\tregistry := dns.NewTransportRegistry()\n\n\ttransport.RegisterTCP(registry)\n\ttransport.RegisterUDP(registry)\n\ttransport.RegisterTLS(registry)\n\ttransport.RegisterHTTPS(registry)\n\thosts.RegisterTransport(registry)\n\tlocal.RegisterTransport(registry)\n\tfakeip.RegisterTransport(registry)\n\n\tquic.RegisterTransport(registry)\n\tquic.RegisterHTTP3Transport(registry)\n\tdhcp.RegisterTransport(registry)\n\ttailscale.RegistryTransport(registry)\n\n\treturn registry\n}\n\nfunc ServiceRegistry() *service.Registry {\n\tregistry := service.NewRegistry()\n\n\tresolved.RegisterService(registry)\n\tssmapi.RegisterService(registry)\n\n\tderp.Register(registry)\n\tccm.RegisterService(registry)\n\tocm.RegisterService(registry)\n\n\treturn registry\n}\n"
  },
  {
    "path": "core/register_naive.go",
    "content": "//go:build with_naive_outbound\n\npackage core\n\nimport (\n\t\"github.com/sagernet/sing-box/adapter/outbound\"\n\t\"github.com/sagernet/sing-box/protocol/naive\"\n)\n\nfunc registerNaiveOutbound(registry *outbound.Registry) {\n\tnaive.RegisterOutbound(registry)\n}\n"
  },
  {
    "path": "core/register_naive_stub.go",
    "content": "//go:build !with_naive_outbound\n\npackage core\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/sagernet/sing-box/adapter/outbound\"\n)\n\nfunc registerNaiveOutbound(registry *outbound.Registry) {\n\t// naive outbound is disabled when built without with_naive_outbound tag\n\tlogger.Error(\"naive outbound is disabled when built without with_naive_outbound tag\")\n}\n"
  },
  {
    "path": "core/tracker_conn.go",
    "content": "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\"github.com/sagernet/sing/common/network\"\n)\n\ntype ConnectionInfo struct {\n\tID         string\n\tConn       net.Conn\n\tPacketConn network.PacketConn\n\tInbound    string\n\tType       string // \"tcp\" or \"udp\"\n}\n\ntype ConnTracker struct {\n\taccess      sync.Mutex\n\tconnections map[string]*ConnectionInfo\n}\n\nfunc NewConnTracker() *ConnTracker {\n\treturn &ConnTracker{\n\t\tconnections: make(map[string]*ConnectionInfo),\n\t}\n}\n\nfunc (c *ConnTracker) generateConnectionID() string {\n\treturn uuid.Must(uuid.NewV4()).String()\n}\n\nfunc (c *ConnTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn {\n\tconnID := c.generateConnectionID()\n\tconnInfo := &ConnectionInfo{\n\t\tID:      connID,\n\t\tConn:    conn,\n\t\tInbound: metadata.Inbound,\n\t\tType:    \"tcp\",\n\t}\n\n\tc.trackConnection(connID, connInfo)\n\n\treturn c.createWrappedConn(conn, connID)\n}\n\nfunc (c *ConnTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn {\n\tconnID := c.generateConnectionID()\n\tconnInfo := &ConnectionInfo{\n\t\tID:         connID,\n\t\tPacketConn: conn,\n\t\tInbound:    metadata.Inbound,\n\t\tType:       \"udp\",\n\t}\n\n\tc.trackConnection(connID, connInfo)\n\n\treturn c.createWrappedPacketConn(conn, connID)\n}\n\nfunc (c *ConnTracker) CloseConnByInbound(inbound string) int {\n\tc.access.Lock()\n\tdefer c.access.Unlock()\n\n\tclosedCount := 0\n\tfor connID, connInfo := range c.connections {\n\t\tif connInfo.Inbound == inbound {\n\t\t\tif connInfo.Conn != nil {\n\t\t\t\tconnInfo.Conn.Close()\n\t\t\t}\n\t\t\tif connInfo.PacketConn != nil {\n\t\t\t\tconnInfo.PacketConn.Close()\n\t\t\t}\n\t\t\tdelete(c.connections, connID)\n\t\t\tclosedCount++\n\t\t}\n\t}\n\treturn closedCount\n}\n\nfunc (c *ConnTracker) trackConnection(connID string, connInfo *ConnectionInfo) {\n\tc.access.Lock()\n\tdefer c.access.Unlock()\n\tc.connections[connID] = connInfo\n}\n\nfunc (c *ConnTracker) untrackConnection(connID string) {\n\tc.access.Lock()\n\tdefer c.access.Unlock()\n\tdelete(c.connections, connID)\n}\n\nfunc (c *ConnTracker) createWrappedConn(conn net.Conn, connID string) *wrappedConn {\n\treturn &wrappedConn{\n\t\tConn:   conn,\n\t\tconnID: connID,\n\t}\n}\n\nfunc (c *ConnTracker) createWrappedPacketConn(conn network.PacketConn, connID string) *wrappedPacketConn {\n\treturn &wrappedPacketConn{\n\t\tPacketConn: conn,\n\t\tconnID:     connID,\n\t}\n}\n\ntype wrappedConn struct {\n\tnet.Conn\n\tconnID string\n}\n\nfunc (w *wrappedConn) Close() error {\n\tconnTracker.untrackConnection(w.connID)\n\treturn w.Conn.Close()\n}\n\nfunc (w *wrappedConn) Upstream() any {\n\treturn w.Conn\n}\n\ntype wrappedPacketConn struct {\n\tnetwork.PacketConn\n\tconnID string\n}\n\nfunc (w *wrappedPacketConn) Close() error {\n\tconnTracker.untrackConnection(w.connID)\n\treturn w.PacketConn.Close()\n}\n\nfunc (w *wrappedPacketConn) Upstream() any {\n\treturn w.PacketConn\n}\n"
  },
  {
    "path": "core/tracker_stats.go",
    "content": "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/sagernet/sing-box/adapter\"\n\t\"github.com/sagernet/sing/common/atomic\"\n\t\"github.com/sagernet/sing/common/bufio\"\n\t\"github.com/sagernet/sing/common/network\"\n)\n\ntype Counter struct {\n\tread  *atomic.Int64\n\twrite *atomic.Int64\n}\n\ntype StatsTracker struct {\n\taccess    sync.Mutex\n\tinbounds  map[string]Counter\n\toutbounds map[string]Counter\n\tusers     map[string]Counter\n}\n\nfunc NewStatsTracker() *StatsTracker {\n\treturn &StatsTracker{\n\t\tinbounds:  make(map[string]Counter),\n\t\toutbounds: make(map[string]Counter),\n\t\tusers:     make(map[string]Counter),\n\t}\n}\n\nfunc (c *StatsTracker) getReadCounters(inbound string, outbound string, user string) ([]*atomic.Int64, []*atomic.Int64) {\n\tvar readCounter []*atomic.Int64\n\tvar writeCounter []*atomic.Int64\n\tc.access.Lock()\n\tdefer c.access.Unlock()\n\n\tif inbound != \"\" {\n\t\treadCounter = append(readCounter, c.loadOrCreateCounter(&c.inbounds, inbound).read)\n\t\twriteCounter = append(writeCounter, c.inbounds[inbound].write)\n\t}\n\tif outbound != \"\" {\n\t\treadCounter = append(readCounter, c.loadOrCreateCounter(&c.outbounds, outbound).read)\n\t\twriteCounter = append(writeCounter, c.outbounds[outbound].write)\n\t}\n\tif user != \"\" {\n\t\treadCounter = append(readCounter, c.loadOrCreateCounter(&c.users, user).read)\n\t\twriteCounter = append(writeCounter, c.users[user].write)\n\t}\n\treturn readCounter, writeCounter\n}\n\nfunc (c *StatsTracker) loadOrCreateCounter(obj *map[string]Counter, name string) Counter {\n\tcounter, loaded := (*obj)[name]\n\tif loaded {\n\t\treturn counter\n\t}\n\tcounter = Counter{read: &atomic.Int64{}, write: &atomic.Int64{}}\n\t(*obj)[name] = counter\n\treturn counter\n}\n\nfunc (c *StatsTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn {\n\treadCounter, writeCounter := c.getReadCounters(metadata.Inbound, matchOutbound.Tag(), metadata.User)\n\treturn bufio.NewInt64CounterConn(conn, readCounter, writeCounter)\n}\n\nfunc (c *StatsTracker) RoutedPacketConnection(ctx context.Context, conn network.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) network.PacketConn {\n\treadCounter, writeCounter := c.getReadCounters(metadata.Inbound, matchOutbound.Tag(), metadata.User)\n\treturn bufio.NewInt64CounterPacketConn(conn, readCounter, nil, writeCounter, nil)\n}\n\nfunc (c *StatsTracker) GetStats() *[]model.Stats {\n\tc.access.Lock()\n\tdefer c.access.Unlock()\n\n\tdt := time.Now().Unix()\n\n\ts := []model.Stats{}\n\tfor inbound, counter := range c.inbounds {\n\t\tdown := counter.write.Swap(0)\n\t\tup := counter.read.Swap(0)\n\t\tif down > 0 || up > 0 {\n\t\t\ts = append(s, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"inbound\",\n\t\t\t\tTag:       inbound,\n\t\t\t\tDirection: false,\n\t\t\t\tTraffic:   down,\n\t\t\t}, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"inbound\",\n\t\t\t\tTag:       inbound,\n\t\t\t\tDirection: true,\n\t\t\t\tTraffic:   up,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor outbound, counter := range c.outbounds {\n\t\tdown := counter.write.Swap(0)\n\t\tup := counter.read.Swap(0)\n\t\tif down > 0 || up > 0 {\n\t\t\ts = append(s, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"outbound\",\n\t\t\t\tTag:       outbound,\n\t\t\t\tDirection: false,\n\t\t\t\tTraffic:   down,\n\t\t\t}, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"outbound\",\n\t\t\t\tTag:       outbound,\n\t\t\t\tDirection: true,\n\t\t\t\tTraffic:   up,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor user, counter := range c.users {\n\t\tdown := counter.write.Swap(0)\n\t\tup := counter.read.Swap(0)\n\t\tif down > 0 || up > 0 {\n\t\t\ts = append(s, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"user\",\n\t\t\t\tTag:       user,\n\t\t\t\tDirection: false,\n\t\t\t\tTraffic:   down,\n\t\t\t}, model.Stats{\n\t\t\t\tDateTime:  dt,\n\t\t\t\tResource:  \"user\",\n\t\t\t\tTag:       user,\n\t\t\t\tDirection: true,\n\t\t\t\tTraffic:   up,\n\t\t\t})\n\t\t}\n\t}\n\treturn &s\n}\n"
  },
  {
    "path": "cronjob/WALCheckpointJob.go",
    "content": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/logger\"\n)\n\ntype WALCheckpointJob struct{}\n\nfunc NewWALCheckpointJob() *WALCheckpointJob {\n\treturn &WALCheckpointJob{}\n}\n\nfunc (s *WALCheckpointJob) Run() {\n\tdb := database.GetDB()\n\t_, err := db.Raw(\"PRAGMA wal_checkpoint(FULL)\").Rows()\n\tif err != nil {\n\t\tlogger.Error(\"Error checkpointing WAL: \", err.Error())\n\t}\n}\n"
  },
  {
    "path": "cronjob/checkCoreJob.go",
    "content": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/service\"\n)\n\ntype CheckCoreJob struct {\n\tservice.ConfigService\n}\n\nfunc NewCheckCoreJob() *CheckCoreJob {\n\treturn &CheckCoreJob{}\n}\n\nfunc (s *CheckCoreJob) Run() {\n\ts.ConfigService.StartCore()\n}\n"
  },
  {
    "path": "cronjob/cronJob.go",
    "content": "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 NewCronJob() *CronJob {\n\treturn &CronJob{}\n}\n\nfunc (c *CronJob) Start(loc *time.Location, trafficAge int) error {\n\tc.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())\n\tc.cron.Start()\n\n\tgo func() {\n\t\t// Start stats job\n\t\tc.cron.AddJob(\"@every 10s\", NewStatsJob(trafficAge > 0))\n\t\t// Start expiry job\n\t\tc.cron.AddJob(\"@every 1m\", NewDepleteJob())\n\t\t// Start deleting old stats\n\t\tif trafficAge > 0 {\n\t\t\tc.cron.AddJob(\"@daily\", NewDelStatsJob(trafficAge))\n\t\t}\n\t\t// Start core if it is not running\n\t\tc.cron.AddJob(\"@every 5s\", NewCheckCoreJob())\n\t\t// database WAL checkpoint\n\t\tc.cron.AddJob(\"@every 10m\", NewWALCheckpointJob())\n\t}()\n\n\treturn nil\n}\n\nfunc (c *CronJob) Stop() {\n\tif c.cron != nil {\n\t\tc.cron.Stop()\n\t}\n}\n"
  },
  {
    "path": "cronjob/delStatsJob.go",
    "content": "package cronjob\n\nimport (\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/service\"\n)\n\ntype DelStatsJob struct {\n\tservice.StatsService\n\ttrafficAge int\n}\n\nfunc NewDelStatsJob(ta int) *DelStatsJob {\n\treturn &DelStatsJob{\n\t\ttrafficAge: ta,\n\t}\n}\n\nfunc (s *DelStatsJob) Run() {\n\terr := s.StatsService.DelOldStats(s.trafficAge)\n\tif err != nil {\n\t\tlogger.Warning(\"Deleting old statistics failed: \", err)\n\t\treturn\n\t}\n\tlogger.Debug(\"Stats older than \", s.trafficAge, \" days were deleted\")\n}\n"
  },
  {
    "path": "cronjob/depleteJob.go",
    "content": "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/s-ui/service\"\n)\n\ntype DepleteJob struct {\n\tservice.ClientService\n\tservice.InboundService\n}\n\nfunc NewDepleteJob() *DepleteJob {\n\treturn new(DepleteJob)\n}\n\nfunc (s *DepleteJob) Run() {\n\tinboundIds, err := s.ClientService.DepleteClients()\n\tif err != nil {\n\t\tlogger.Warning(\"Disable depleted users failed: \", err)\n\t\treturn\n\t}\n\tif len(inboundIds) > 0 {\n\t\terr := s.InboundService.RestartInbounds(database.GetDB(), inboundIds)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"unable to restart inbounds: \", err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "cronjob/statsJob.go",
    "content": "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 {\n\tservice.StatsService\n\tenableTraffic bool\n}\n\nfunc NewStatsJob(saveTraffic bool) *StatsJob {\n\treturn &StatsJob{\n\t\tenableTraffic: saveTraffic,\n\t}\n}\n\nfunc (s *StatsJob) Run() {\n\terr := s.StatsService.SaveStats(s.enableTraffic)\n\tif err != nil {\n\t\tlogger.Warning(\"Get stats failed: \", err)\n\t\treturn\n\t}\n}\n"
  },
  {
    "path": "database/backup.go",
    "content": "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\"syscall\"\n\t\"time\"\n\n\t\"github.com/alireza0/s-ui/cmd/migration\"\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/driver/sqlite\"\n\t\"gorm.io/gorm\"\n)\n\nfunc GetDb(exclude string) ([]byte, error) {\n\texclude_changes, exclude_stats := false, false\n\tfor _, table := range strings.Split(exclude, \",\") {\n\t\tif table == \"changes\" {\n\t\t\texclude_changes = true\n\t\t} else if table == \"stats\" {\n\t\t\texclude_stats = true\n\t\t}\n\t}\n\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbPath := dir + config.GetName() + \"_\" + time.Now().Format(\"20060102-200203\") + \".db\"\n\n\tbackupDb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.Remove(dbPath)\n\n\terr = backupDb.AutoMigrate(\n\t\t&model.Setting{},\n\t\t&model.Tls{},\n\t\t&model.Inbound{},\n\t\t&model.Outbound{},\n\t\t&model.Endpoint{},\n\t\t&model.User{},\n\t\t&model.Stats{},\n\t\t&model.Client{},\n\t\t&model.Changes{},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar settings []model.Setting\n\tvar tls []model.Tls\n\tvar inbound []model.Inbound\n\tvar outbound []model.Outbound\n\tvar endpoint []model.Endpoint\n\tvar users []model.User\n\tvar clients []model.Client\n\tvar stats []model.Stats\n\tvar changes []model.Changes\n\n\t// Perform scans and handle errors\n\tif err := db.Model(&model.Setting{}).Scan(&settings).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(settings) > 0 {\n\t\tif err := backupDb.Save(settings).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.Tls{}).Scan(&tls).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(tls) > 0 {\n\t\tif err := backupDb.Save(tls).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.Inbound{}).Scan(&inbound).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(inbound) > 0 {\n\t\tif err := backupDb.Save(inbound).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.Outbound{}).Scan(&outbound).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(outbound) > 0 {\n\t\tif err := backupDb.Save(outbound).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.Endpoint{}).Scan(&endpoint).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(endpoint) > 0 {\n\t\tif err := backupDb.Save(endpoint).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.User{}).Scan(&users).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(users) > 0 {\n\t\tif err := backupDb.Save(users).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := db.Model(&model.Client{}).Scan(&clients).Error; err != nil {\n\t\treturn nil, err\n\t} else if len(clients) > 0 {\n\t\tif err := backupDb.Save(clients).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif !exclude_stats {\n\t\tif err := db.Model(&model.Stats{}).Scan(&stats).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(stats) > 0 {\n\t\t\tif err := backupDb.Save(stats).Error; err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tif !exclude_changes {\n\t\tif err := db.Model(&model.Changes{}).Scan(&changes).Error; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(changes) > 0 {\n\t\t\tif err := backupDb.Save(changes).Error; err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Update WAL\n\terr = backupDb.Exec(\"PRAGMA wal_checkpoint;\").Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbdb, _ := backupDb.DB()\n\tbdb.Close()\n\n\t// Open the file for reading\n\tfile, err := os.Open(dbPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\t// Read the file contents\n\tfileContents, err := io.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fileContents, nil\n}\n\nfunc ImportDB(file multipart.File) error {\n\t// Check if the file is a SQLite database\n\tisValidDb, err := IsSQLiteDB(file)\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error checking db file format: %v\", err)\n\t}\n\tif !isValidDb {\n\t\treturn common.NewError(\"Invalid db file format\")\n\t}\n\n\t// Reset the file reader to the beginning\n\t_, err = file.Seek(0, 0)\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error resetting file reader: %v\", err)\n\t}\n\n\t// Save the file as temporary file\n\ttempPath := fmt.Sprintf(\"%s.temp\", config.GetDBPath())\n\t// Remove the existing fallback file (if any) before creating one\n\t_, err = os.Stat(tempPath)\n\tif err == nil {\n\t\terrRemove := os.Remove(tempPath)\n\t\tif errRemove != nil {\n\t\t\treturn common.NewErrorf(\"Error removing existing temporary db file: %v\", errRemove)\n\t\t}\n\t}\n\t// Create the temporary file\n\ttempFile, err := os.Create(tempPath)\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error creating temporary db file: %v\", err)\n\t}\n\tdefer tempFile.Close()\n\n\t// Remove temp file before returning\n\tdefer os.Remove(tempPath)\n\n\t// Close old DB\n\told_db, _ := db.DB()\n\told_db.Close()\n\n\t// Save uploaded file to temporary file\n\t_, err = io.Copy(tempFile, file)\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error saving db: %v\", err)\n\t}\n\n\t// Check if we can init db or not\n\tnewDb, err := gorm.Open(sqlite.Open(tempPath), &gorm.Config{})\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error checking db: %v\", err)\n\t}\n\tnewDb_db, _ := newDb.DB()\n\tnewDb_db.Close()\n\n\t// Backup the current database for fallback\n\tfallbackPath := fmt.Sprintf(\"%s.backup\", config.GetDBPath())\n\t// Remove the existing fallback file (if any)\n\t_, err = os.Stat(fallbackPath)\n\tif err == nil {\n\t\terrRemove := os.Remove(fallbackPath)\n\t\tif errRemove != nil {\n\t\t\treturn common.NewErrorf(\"Error removing existing fallback db file: %v\", errRemove)\n\t\t}\n\t}\n\t// Move the current database to the fallback location\n\terr = os.Rename(config.GetDBPath(), fallbackPath)\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error backing up temporary db file: %v\", err)\n\t}\n\n\t// Remove the temporary file before returning\n\tdefer os.Remove(fallbackPath)\n\n\t// Move temp to DB path\n\terr = os.Rename(tempPath, config.GetDBPath())\n\tif err != nil {\n\t\terrRename := os.Rename(fallbackPath, config.GetDBPath())\n\t\tif errRename != nil {\n\t\t\treturn common.NewErrorf(\"Error moving db file and restoring fallback: %v\", errRename)\n\t\t}\n\t\treturn common.NewErrorf(\"Error moving db file: %v\", err)\n\t}\n\n\t// Migrate DB\n\tmigration.MigrateDb()\n\terr = InitDB(config.GetDBPath())\n\tif err != nil {\n\t\terrRename := os.Rename(fallbackPath, config.GetDBPath())\n\t\tif errRename != nil {\n\t\t\treturn common.NewErrorf(\"Error migrating db and restoring fallback: %v\", errRename)\n\t\t}\n\t\treturn common.NewErrorf(\"Error migrating db: %v\", err)\n\t}\n\n\t// Restart app\n\terr = SendSighup()\n\tif err != nil {\n\t\treturn common.NewErrorf(\"Error restarting app: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc IsSQLiteDB(file io.Reader) (bool, error) {\n\tsignature := []byte(\"SQLite format 3\\x00\")\n\tbuf := make([]byte, len(signature))\n\t_, err := file.Read(buf)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(buf, signature), nil\n}\n\nfunc SendSighup() error {\n\t// Get the current process\n\tprocess, err := os.FindProcess(os.Getpid())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Send SIGHUP to the current process\n\tgo func() {\n\t\ttime.Sleep(3 * time.Second)\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\terr = process.Kill()\n\t\t} else {\n\t\t\terr = process.Signal(syscall.SIGHUP)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.Error(\"send signal SIGHUP failed:\", err)\n\t\t}\n\t}()\n\treturn nil\n}\n"
  },
  {
    "path": "database/db.go",
    "content": "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/alireza0/s-ui/database/model\"\n\n\t\"gorm.io/driver/sqlite\"\n\t\"gorm.io/gorm\"\n\t\"gorm.io/gorm/logger\"\n)\n\nvar db *gorm.DB\n\nfunc initUser() error {\n\tvar count int64\n\terr := db.Model(&model.User{}).Count(&count).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count == 0 {\n\t\tuser := &model.User{\n\t\t\tUsername: \"admin\",\n\t\t\tPassword: \"admin\",\n\t\t}\n\t\treturn db.Create(user).Error\n\t}\n\treturn nil\n}\n\nfunc OpenDB(dbPath string) error {\n\tdir := path.Dir(dbPath)\n\terr := os.MkdirAll(dir, 01740)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar gormLogger logger.Interface\n\n\tif config.IsDebug() {\n\t\tgormLogger = logger.Default\n\t} else {\n\t\tgormLogger = logger.Discard\n\t}\n\n\tc := &gorm.Config{\n\t\tLogger: gormLogger,\n\t}\n\tsep := \"?\"\n\tif strings.Contains(dbPath, \"?\") {\n\t\tsep = \"&\"\n\t}\n\tdsn := dbPath + sep + \"_busy_timeout=10000&_journal_mode=WAL\"\n\tdb, err = gorm.Open(sqlite.Open(dsn), c)\n\n\tif config.IsDebug() {\n\t\tdb = db.Debug()\n\t}\n\treturn err\n}\n\nfunc InitDB(dbPath string) error {\n\terr := OpenDB(dbPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Default Outbounds\n\tif !db.Migrator().HasTable(&model.Outbound{}) {\n\t\tdb.Migrator().CreateTable(&model.Outbound{})\n\t\tdefaultOutbound := []model.Outbound{\n\t\t\t{Type: \"direct\", Tag: \"direct\", Options: json.RawMessage(`{}`)},\n\t\t}\n\t\tdb.Create(&defaultOutbound)\n\t}\n\n\terr = db.AutoMigrate(\n\t\t&model.Setting{},\n\t\t&model.Tls{},\n\t\t&model.Inbound{},\n\t\t&model.Outbound{},\n\t\t&model.Service{},\n\t\t&model.Endpoint{},\n\t\t&model.User{},\n\t\t&model.Tokens{},\n\t\t&model.Stats{},\n\t\t&model.Client{},\n\t\t&model.Changes{},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = initUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc GetDB() *gorm.DB {\n\treturn db\n}\n\nfunc IsNotFound(err error) bool {\n\treturn err == gorm.ErrRecordNotFound\n}\n"
  },
  {
    "path": "database/model/endpoints.go",
    "content": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Endpoint struct {\n\tId      uint            `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tType    string          `json:\"type\" form:\"type\"`\n\tTag     string          `json:\"tag\" form:\"tag\" gorm:\"unique\"`\n\tOptions json.RawMessage `json:\"-\" form:\"-\"`\n\tExt     json.RawMessage `json:\"ext\" form:\"ext\"`\n}\n\nfunc (o *Endpoint) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar raw map[string]interface{}\n\tif err = json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\t// Extract fixed fields and store the rest in Options\n\tif val, exists := raw[\"id\"].(float64); exists {\n\t\to.Id = uint(val)\n\t}\n\tdelete(raw, \"id\")\n\to.Type, _ = raw[\"type\"].(string)\n\tdelete(raw, \"type\")\n\to.Tag = raw[\"tag\"].(string)\n\tdelete(raw, \"tag\")\n\to.Ext, _ = json.MarshalIndent(raw[\"ext\"], \"\", \"  \")\n\tdelete(raw, \"ext\")\n\n\t// Remaining fields\n\to.Options, err = json.MarshalIndent(raw, \"\", \"  \")\n\treturn err\n}\n\n// MarshalJSON customizes marshalling\nfunc (o Endpoint) MarshalJSON() ([]byte, error) {\n\t// Combine fixed fields and dynamic fields into one map\n\tcombined := make(map[string]interface{})\n\tswitch o.Type {\n\tcase \"warp\":\n\t\tcombined[\"type\"] = \"wireguard\"\n\tdefault:\n\t\tcombined[\"type\"] = o.Type\n\t}\n\tcombined[\"tag\"] = o.Tag\n\n\tif o.Options != nil {\n\t\tvar restFields map[string]json.RawMessage\n\t\tif err := json.Unmarshal(o.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(combined)\n}\n"
  },
  {
    "path": "database/model/inbounds.go",
    "content": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Inbound struct {\n\tId   uint   `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tType string `json:\"type\" form:\"type\"`\n\tTag  string `json:\"tag\" form:\"tag\" gorm:\"unique\"`\n\n\t// Foreign key to tls table\n\tTlsId uint `json:\"tls_id\" form:\"tls_id\"`\n\tTls   *Tls `json:\"tls\" form:\"tls\" gorm:\"foreignKey:TlsId;references:Id\"`\n\n\tAddrs   json.RawMessage `json:\"addrs\" form:\"addrs\"`\n\tOutJson json.RawMessage `json:\"out_json\" form:\"out_json\"`\n\tOptions json.RawMessage `json:\"-\" form:\"-\"`\n}\n\nfunc (i *Inbound) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar raw map[string]interface{}\n\tif err = json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\t// Extract fixed fields and store the rest in Options\n\tif val, exists := raw[\"id\"].(float64); exists {\n\t\ti.Id = uint(val)\n\t}\n\tdelete(raw, \"id\")\n\ti.Type, _ = raw[\"type\"].(string)\n\tdelete(raw, \"type\")\n\ti.Tag, _ = raw[\"tag\"].(string)\n\tdelete(raw, \"tag\")\n\n\t// TlsId\n\tif val, exists := raw[\"tls_id\"].(float64); exists {\n\t\ti.TlsId = uint(val)\n\t}\n\tdelete(raw, \"tls_id\")\n\tdelete(raw, \"tls\")\n\tdelete(raw, \"users\")\n\n\t// Addrs\n\ti.Addrs, _ = json.MarshalIndent(raw[\"addrs\"], \"\", \"  \")\n\tdelete(raw, \"addrs\")\n\n\t// OutJson\n\ti.OutJson, _ = json.MarshalIndent(raw[\"out_json\"], \"\", \"  \")\n\tdelete(raw, \"out_json\")\n\n\t// Remaining fields\n\ti.Options, err = json.MarshalIndent(raw, \"\", \"  \")\n\treturn err\n}\n\n// MarshalJSON customizes marshalling\nfunc (i Inbound) MarshalJSON() ([]byte, error) {\n\t// Combine fixed fields and dynamic fields into one map\n\tcombined := make(map[string]interface{})\n\tcombined[\"type\"] = i.Type\n\tcombined[\"tag\"] = i.Tag\n\tif i.Tls != nil {\n\t\tcombined[\"tls\"] = i.Tls.Server\n\t}\n\n\tif i.Options != nil {\n\t\tvar restFields map[string]json.RawMessage\n\t\tif err := json.Unmarshal(i.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(combined)\n}\n\nfunc (i Inbound) MarshalFull() (*map[string]interface{}, error) {\n\tcombined := make(map[string]interface{})\n\tcombined[\"id\"] = i.Id\n\tcombined[\"type\"] = i.Type\n\tcombined[\"tag\"] = i.Tag\n\tcombined[\"tls_id\"] = i.TlsId\n\tcombined[\"addrs\"] = i.Addrs\n\tcombined[\"out_json\"] = i.OutJson\n\n\tif i.Options != nil {\n\t\tvar restFields map[string]interface{}\n\t\tif err := json.Unmarshal(i.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\treturn &combined, nil\n}\n"
  },
  {
    "path": "database/model/model.go",
    "content": "package model\n\nimport \"encoding/json\"\n\ntype Setting struct {\n\tId    uint   `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tKey   string `json:\"key\" form:\"key\"`\n\tValue string `json:\"value\" form:\"value\"`\n}\n\ntype Tls struct {\n\tId     uint            `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tName   string          `json:\"name\" form:\"name\"`\n\tServer json.RawMessage `json:\"server\" form:\"server\"`\n\tClient json.RawMessage `json:\"client\" form:\"client\"`\n}\n\ntype User struct {\n\tId         uint   `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tUsername   string `json:\"username\" form:\"username\"`\n\tPassword   string `json:\"password\" form:\"password\"`\n\tLastLogins string `json:\"lastLogin\"`\n}\n\ntype Client struct {\n\tId       uint            `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tEnable   bool            `json:\"enable\" form:\"enable\"`\n\tName     string          `json:\"name\" form:\"name\"`\n\tConfig   json.RawMessage `json:\"config,omitempty\" form:\"config\"`\n\tInbounds json.RawMessage `json:\"inbounds\" form:\"inbounds\"`\n\tLinks    json.RawMessage `json:\"links,omitempty\" form:\"links\"`\n\tVolume   int64           `json:\"volume\" form:\"volume\"`\n\tExpiry   int64           `json:\"expiry\" form:\"expiry\"`\n\tDown     int64           `json:\"down\" form:\"down\"`\n\tUp       int64           `json:\"up\" form:\"up\"`\n\tDesc     string          `json:\"desc\" form:\"desc\"`\n\tGroup    string          `json:\"group\" form:\"group\"`\n\n\t// Delay start and periodic reset\n\tDelayStart bool  `json:\"delayStart\" form:\"delayStart\" gorm:\"default:false;not null\"`\n\tAutoReset  bool  `json:\"autoReset\" form:\"autoReset\" gorm:\"default:false;not null\"`\n\tResetDays  int   `json:\"resetDays\" form:\"resetDays\" gorm:\"default:0;not null\"`\n\tNextReset  int64 `json:\"nextReset\" form:\"nextReset\" gorm:\"default:0;not null\"`\n\tTotalUp    int64 `json:\"totalUp\" form:\"totalUp\" gorm:\"default:0;not null\"`\n\tTotalDown  int64 `json:\"totalDown\" form:\"totalDown\" gorm:\"default:0;not null\"`\n}\n\ntype Stats struct {\n\tId        uint64 `json:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tDateTime  int64  `json:\"dateTime\"`\n\tResource  string `json:\"resource\"`\n\tTag       string `json:\"tag\"`\n\tDirection bool   `json:\"direction\"`\n\tTraffic   int64  `json:\"traffic\"`\n}\n\ntype Changes struct {\n\tId       uint64          `json:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tDateTime int64           `json:\"dateTime\"`\n\tActor    string          `json:\"actor\"`\n\tKey      string          `json:\"key\"`\n\tAction   string          `json:\"action\"`\n\tObj      json.RawMessage `json:\"obj\"`\n}\n\ntype Tokens struct {\n\tId     uint   `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tDesc   string `json:\"desc\" form:\"desc\"`\n\tToken  string `json:\"token\" form:\"token\"`\n\tExpiry int64  `json:\"expiry\" form:\"expiry\"`\n\tUserId uint   `json:\"userId\" form:\"userId\"`\n\tUser   *User  `json:\"user\" gorm:\"foreignKey:UserId;references:Id\"`\n}\n"
  },
  {
    "path": "database/model/outbounds.go",
    "content": "package model\n\nimport \"encoding/json\"\n\ntype Outbound struct {\n\tId      uint            `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tType    string          `json:\"type\" form:\"type\"`\n\tTag     string          `json:\"tag\" form:\"tag\" gorm:\"unique\"`\n\tOptions json.RawMessage `json:\"-\" form:\"-\"`\n}\n\nfunc (o *Outbound) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar raw map[string]interface{}\n\tif err = json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\t// Extract fixed fields and store the rest in Options\n\tif val, exists := raw[\"id\"].(float64); exists {\n\t\to.Id = uint(val)\n\t}\n\tdelete(raw, \"id\")\n\to.Type, _ = raw[\"type\"].(string)\n\tdelete(raw, \"type\")\n\to.Tag = raw[\"tag\"].(string)\n\tdelete(raw, \"tag\")\n\n\t// Remaining fields\n\to.Options, err = json.MarshalIndent(raw, \"\", \"  \")\n\treturn err\n}\n\n// MarshalJSON customizes marshalling\nfunc (o Outbound) MarshalJSON() ([]byte, error) {\n\t// Combine fixed fields and dynamic fields into one map\n\tcombined := make(map[string]interface{})\n\tcombined[\"type\"] = o.Type\n\tcombined[\"tag\"] = o.Tag\n\n\tif o.Options != nil {\n\t\tvar restFields map[string]json.RawMessage\n\t\tif err := json.Unmarshal(o.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(combined)\n}\n"
  },
  {
    "path": "database/model/services.go",
    "content": "package model\n\nimport (\n\t\"encoding/json\"\n)\n\ntype Service struct {\n\tId   uint   `json:\"id\" form:\"id\" gorm:\"primaryKey;autoIncrement\"`\n\tType string `json:\"type\" form:\"type\"`\n\tTag  string `json:\"tag\" form:\"tag\" gorm:\"unique\"`\n\n\t// Foreign key to tls table\n\tTlsId uint `json:\"tls_id\" form:\"tls_id\"`\n\tTls   *Tls `json:\"tls\" form:\"tls\" gorm:\"foreignKey:TlsId;references:Id\"`\n\n\tOptions json.RawMessage `json:\"-\" form:\"-\"`\n}\n\nfunc (i *Service) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar raw map[string]interface{}\n\tif err = json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\t// Extract fixed fields and store the rest in Options\n\tif val, exists := raw[\"id\"].(float64); exists {\n\t\ti.Id = uint(val)\n\t}\n\tdelete(raw, \"id\")\n\ti.Type, _ = raw[\"type\"].(string)\n\tdelete(raw, \"type\")\n\ti.Tag, _ = raw[\"tag\"].(string)\n\tdelete(raw, \"tag\")\n\n\t// TlsId\n\tif val, exists := raw[\"tls_id\"].(float64); exists {\n\t\ti.TlsId = uint(val)\n\t}\n\tdelete(raw, \"tls_id\")\n\tdelete(raw, \"tls\")\n\n\t// Remaining fields\n\ti.Options, err = json.MarshalIndent(raw, \"\", \"  \")\n\treturn err\n}\n\n// MarshalJSON customizes marshalling\nfunc (i Service) MarshalJSON() ([]byte, error) {\n\t// Combine fixed fields and dynamic fields into one map\n\tcombined := make(map[string]interface{})\n\tcombined[\"type\"] = i.Type\n\tcombined[\"tag\"] = i.Tag\n\tif i.Tls != nil {\n\t\tcombined[\"tls\"] = i.Tls.Server\n\t}\n\n\tif i.Options != nil {\n\t\tvar restFields map[string]json.RawMessage\n\t\tif err := json.Unmarshal(i.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(combined)\n}\n\nfunc (i Service) MarshalFull() (*map[string]interface{}, error) {\n\tcombined := make(map[string]interface{})\n\tcombined[\"id\"] = i.Id\n\tcombined[\"type\"] = i.Type\n\tcombined[\"tag\"] = i.Tag\n\tcombined[\"tls_id\"] = i.TlsId\n\n\tif i.Options != nil {\n\t\tvar restFields map[string]interface{}\n\t\tif err := json.Unmarshal(i.Options, &restFields); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range restFields {\n\t\t\tcombined[k] = v\n\t\t}\n\t}\n\treturn &combined, nil\n}\n"
  },
  {
    "path": "docker-build-test.sh",
    "content": "#!/usr/bin/env bash\n# Test Docker multi-platform build (linux/amd64, 386, arm64, arm/v7, arm/v6)\n# Requires: frontend_dist/ (run from repo root after building frontend)\n\nset -e\ncd \"$(dirname \"$0\")/..\"\n\necho \"==> Preparing frontend_dist...\"\nif [ ! -d \"frontend_dist\" ] || [ -z \"$(ls -A frontend_dist 2>/dev/null)\" ]; then\n  echo \"Building frontend...\"\n  (cd frontend && npm install --prefer-offline --no-audit && npm run build)\n  rm -rf frontend_dist\n  mkdir -p frontend_dist\n  cp -R frontend/dist/* frontend_dist/\n  echo \"frontend_dist ready.\"\nelse\n  echo \"frontend_dist exists, skipping frontend build.\"\nfi\n\nPLATFORMS=\"linux/amd64,linux/386,linux/arm64/v8,linux/arm/v7,linux/arm/v6\"\necho \"==> Testing Docker build for: $PLATFORMS\"\ndocker buildx build \\\n  --platform \"$PLATFORMS\" \\\n  -f Dockerfile.frontend-artifact \\\n  --build-arg CRONET_RELEASE=latest \\\n  --progress=plain \\\n  . 2>&1 | tee docker-build-test.log\n\necho \"==> Done. Check docker-build-test.log for full output.\"\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "---\nservices:\n  s-ui:\n    image: alireza7/s-ui\n    container_name: s-ui\n    hostname: \"s-ui\"\n    volumes:\n      - \"./db:/app/db\"\n      - \"./cert:/app/cert\"\n    tty: true\n    restart: unless-stopped\n    ports:\n      - \"2095:2095\"\n      - \"2096:2096\"\n    networks:\n      - s-ui\n    entrypoint: \"./entrypoint.sh\"\n\nnetworks:\n  s-ui:\n    driver: bridge\n  "
  },
  {
    "path": "entrypoint.sh",
    "content": "#!/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",
    "content": "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/sessions v1.0.4\n\tgithub.com/gin-gonic/gin v1.12.0\n\tgithub.com/gofrs/uuid/v5 v5.4.0\n\tgithub.com/op/go-logging v0.0.0-20160315200505-970db520ece7\n\tgithub.com/robfig/cron/v3 v3.0.1\n\tgithub.com/sagernet/sing v0.8.2\n\tgithub.com/sagernet/sing-box v1.13.2\n\tgithub.com/shirou/gopsutil/v4 v4.26.2\n\tgolang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10\n\tgopkg.in/yaml.v3 v3.0.1\n\tgorm.io/driver/sqlite v1.6.0\n\tgorm.io/gorm v1.31.1\n)\n\nrequire (\n\tfilippo.io/edwards25519 v1.2.0 // indirect\n\tgithub.com/ajg/form v1.5.1 // indirect\n\tgithub.com/akutz/memconn v0.1.0 // indirect\n\tgithub.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect\n\tgithub.com/andybalholm/brotli v1.1.0 // indirect\n\tgithub.com/anthropics/anthropic-sdk-go v1.26.0 // indirect\n\tgithub.com/anytls/sing-anytls v0.0.11 // indirect\n\tgithub.com/bytedance/gopkg v0.1.3 // indirect\n\tgithub.com/bytedance/sonic v1.15.0 // indirect\n\tgithub.com/bytedance/sonic/loader v0.5.0 // indirect\n\tgithub.com/caddyserver/certmagic v0.25.2 // indirect\n\tgithub.com/caddyserver/zerossl v0.1.5 // indirect\n\tgithub.com/cloudwego/base64x v0.1.6 // indirect\n\tgithub.com/coder/websocket v1.8.14 // indirect\n\tgithub.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6 // indirect\n\tgithub.com/cretz/bine v0.2.0 // indirect\n\tgithub.com/database64128/netx-go v0.1.1 // indirect\n\tgithub.com/database64128/tfo-go/v2 v2.3.2 // indirect\n\tgithub.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/florianl/go-nfqueue/v2 v2.0.2 // indirect\n\tgithub.com/fsnotify/fsnotify v1.7.0 // indirect\n\tgithub.com/fxamacker/cbor/v2 v2.7.0 // indirect\n\tgithub.com/gabriel-vasile/mimetype v1.4.12 // indirect\n\tgithub.com/gaissmai/bart v0.18.0 // indirect\n\tgithub.com/gin-contrib/sse v1.1.0 // indirect\n\tgithub.com/go-chi/chi/v5 v5.2.5 // indirect\n\tgithub.com/go-chi/render v1.0.3 // indirect\n\tgithub.com/go-json-experiment/json v0.0.0-20250813024750-ebf49471dced // indirect\n\tgithub.com/go-ole/go-ole v1.3.0 // indirect\n\tgithub.com/go-playground/locales v0.14.1 // indirect\n\tgithub.com/go-playground/universal-translator v0.18.1 // indirect\n\tgithub.com/go-playground/validator/v10 v10.30.1 // indirect\n\tgithub.com/gobwas/httphead v0.1.0 // indirect\n\tgithub.com/gobwas/pool v0.2.1 // indirect\n\tgithub.com/goccy/go-json v0.10.5 // indirect\n\tgithub.com/goccy/go-yaml v1.19.2 // indirect\n\tgithub.com/godbus/dbus/v5 v5.2.2 // indirect\n\tgithub.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect\n\tgithub.com/google/btree v1.1.3 // indirect\n\tgithub.com/google/go-cmp v0.7.0 // indirect\n\tgithub.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/gorilla/context v1.1.2 // indirect\n\tgithub.com/gorilla/securecookie v1.1.2 // indirect\n\tgithub.com/gorilla/sessions v1.4.0 // indirect\n\tgithub.com/hashicorp/yamux v0.1.2 // indirect\n\tgithub.com/hdevalence/ed25519consensus v0.2.0 // indirect\n\tgithub.com/insomniacslk/dhcp v0.0.0-20260220084031-5adc3eb26f91 // indirect\n\tgithub.com/jinzhu/inflection v1.0.0 // indirect\n\tgithub.com/jinzhu/now v1.1.5 // indirect\n\tgithub.com/jsimonetti/rtnetlink v1.4.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/keybase/go-keychain v0.0.1 // indirect\n\tgithub.com/klauspost/compress v1.18.0 // indirect\n\tgithub.com/klauspost/cpuid/v2 v2.3.0 // indirect\n\tgithub.com/leodido/go-urn v1.4.0 // indirect\n\tgithub.com/libdns/acmedns v0.5.0 // indirect\n\tgithub.com/libdns/alidns v1.0.6 // indirect\n\tgithub.com/libdns/cloudflare v0.2.2 // indirect\n\tgithub.com/libdns/libdns v1.1.1 // indirect\n\tgithub.com/logrusorgru/aurora v2.0.3+incompatible // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect\n\tgithub.com/mattn/go-isatty v0.0.20 // indirect\n\tgithub.com/mattn/go-sqlite3 v1.14.30 // indirect\n\tgithub.com/mdlayher/netlink v1.9.0 // indirect\n\tgithub.com/mdlayher/socket v0.5.1 // indirect\n\tgithub.com/metacubex/utls v1.8.4 // indirect\n\tgithub.com/mholt/acmez/v3 v3.1.6 // indirect\n\tgithub.com/miekg/dns v1.1.72 // indirect\n\tgithub.com/mitchellh/go-ps v1.0.0 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.2 // indirect\n\tgithub.com/openai/openai-go/v3 v3.24.0 // indirect\n\tgithub.com/pelletier/go-toml/v2 v2.2.4 // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.21 // indirect\n\tgithub.com/pires/go-proxyproto v0.8.1 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus-community/pro-bing v0.4.0 // indirect\n\tgithub.com/quic-go/qpack v0.6.0 // indirect\n\tgithub.com/quic-go/quic-go v0.59.0 // indirect\n\tgithub.com/safchain/ethtool v0.3.0 // indirect\n\tgithub.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a // indirect\n\tgithub.com/sagernet/cors v1.2.1 // indirect\n\tgithub.com/sagernet/cronet-go v0.0.0-20260303101018-cba7b9ac0399 // indirect\n\tgithub.com/sagernet/cronet-go/all v0.0.0-20260303101018-cba7b9ac0399 // indirect\n\tgithub.com/sagernet/cronet-go/lib/android_386 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/android_arm v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_loong64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_loong64_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_mips64le v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_mipsle v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_mipsle_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_riscv64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/linux_riscv64_musl v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20260303100323-125d0d93b3e6 // indirect\n\tgithub.com/sagernet/fswatch v0.1.1 // indirect\n\tgithub.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1 // indirect\n\tgithub.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect\n\tgithub.com/sagernet/nftables v0.3.0-beta.4 // indirect\n\tgithub.com/sagernet/quic-go v0.59.0-sing-box-mod.4 // indirect\n\tgithub.com/sagernet/sing-mux v0.3.4 // indirect\n\tgithub.com/sagernet/sing-quic v0.6.0 // indirect\n\tgithub.com/sagernet/sing-shadowsocks v0.2.8 // indirect\n\tgithub.com/sagernet/sing-shadowsocks2 v0.2.1 // indirect\n\tgithub.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11 // indirect\n\tgithub.com/sagernet/sing-tun v0.8.2 // indirect\n\tgithub.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1 // indirect\n\tgithub.com/sagernet/smux v1.5.50-sing-box-mod.1 // indirect\n\tgithub.com/sagernet/tailscale v1.92.4-sing-box-1.13-mod.6.0.20260303140313-3bcf9a4b9349 // indirect\n\tgithub.com/sagernet/wireguard-go v0.0.2-beta.1.0.20260224074747-506b7631853c // indirect\n\tgithub.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 // indirect\n\tgithub.com/tailscale/certstore v0.1.1-0.20231202035212-d3fa0460f47e // indirect\n\tgithub.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect\n\tgithub.com/tailscale/goupnp v1.0.1-0.20210804011211-c64d0f06ea05 // indirect\n\tgithub.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a // indirect\n\tgithub.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7 // indirect\n\tgithub.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect\n\tgithub.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976 // indirect\n\tgithub.com/tidwall/gjson v1.18.0 // indirect\n\tgithub.com/tidwall/match v1.1.1 // indirect\n\tgithub.com/tidwall/pretty v1.2.1 // indirect\n\tgithub.com/tidwall/sjson v1.2.5 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirect\n\tgithub.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 // indirect\n\tgithub.com/ugorji/go/codec v1.3.1 // indirect\n\tgithub.com/vishvananda/netns v0.0.5 // indirect\n\tgithub.com/x448/float16 v0.8.4 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgithub.com/zeebo/blake3 v0.2.4 // indirect\n\tgo.mongodb.org/mongo-driver/v2 v2.5.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.uber.org/zap/exp v0.3.0 // indirect\n\tgo4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect\n\tgo4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect\n\tgolang.org/x/arch v0.22.0 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 // indirect\n\tgolang.org/x/mod v0.33.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/oauth2 v0.34.0 // indirect\n\tgolang.org/x/sync v0.19.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/term v0.40.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgolang.org/x/time v0.12.0 // indirect\n\tgolang.org/x/tools v0.42.0 // indirect\n\tgolang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect\n\tgolang.zx2c4.com/wireguard/windows v0.5.3 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect\n\tgoogle.golang.org/grpc v1.79.1 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tlukechampine.com/blake3 v1.4.1 // indirect\n)\n\nreplace github.com/quic-go/quic-go => github.com/quic-go/quic-go v0.57.1\n"
  },
  {
    "path": "go.sum",
    "content": "code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=\ncode.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=\nfilippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=\nfilippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=\ngithub.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=\ngithub.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=\ngithub.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=\ngithub.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=\ngithub.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=\ngithub.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=\ngithub.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=\ngithub.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=\ngithub.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=\ngithub.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=\ngithub.com/anytls/sing-anytls v0.0.11 h1:w8e9Uj1oP3m4zxkyZDewPk0EcQbvVxb7Nn+rapEx4fc=\ngithub.com/anytls/sing-anytls v0.0.11/go.mod h1:7rjN6IukwysmdusYsrV51Fgu1uW6vsrdd6ctjnEAln8=\ngithub.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=\ngithub.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=\ngithub.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=\ngithub.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=\ngithub.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=\ngithub.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=\ngithub.com/caddyserver/certmagic v0.25.2 h1:D7xcS7ggX/WEY54x0czj7ioTkmDWKIgxtIi2OcQclUc=\ngithub.com/caddyserver/certmagic v0.25.2/go.mod h1:llW/CvsNmza8S6hmsuggsZeiX+uS27dkqY27wDIuBWg=\ngithub.com/caddyserver/zerossl v0.1.5 h1:dkvOjBAEEtY6LIGAHei7sw2UgqSD6TrWweXpV7lvEvE=\ngithub.com/caddyserver/zerossl v0.1.5/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cilium/ebpf v0.15.0 h1:7NxJhNiBT3NG8pZJ3c+yfrVdHY8ScgKD27sScgjLMMk=\ngithub.com/cilium/ebpf v0.15.0/go.mod h1:DHp1WyrLeiBh19Cf/tfiSMhqheEiK8fXFZ4No0P1Hso=\ngithub.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=\ngithub.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=\ngithub.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=\ngithub.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=\ngithub.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6 h1:8h5+bWd7R6AYUslN6c6iuZWTKsKxUFDlpnmilO6R2n0=\ngithub.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q=\ngithub.com/cretz/bine v0.2.0 h1:8GiDRGlTgz+o8H9DSnsl+5MeBK4HsExxgl6WgzOCuZo=\ngithub.com/cretz/bine v0.2.0/go.mod h1:WU4o9QR9wWp8AVKtTM1XD5vUHkEqnf2vVSo6dBqbetI=\ngithub.com/database64128/netx-go v0.1.1 h1:dT5LG7Gs7zFZBthFBbzWE6K8wAHjSNAaK7wCYZT7NzM=\ngithub.com/database64128/netx-go v0.1.1/go.mod h1:LNlYVipaYkQArRFDNNJ02VkNV+My9A5XR/IGS7sIBQc=\ngithub.com/database64128/tfo-go/v2 v2.3.2 h1:UhZMKiMq3swZGUiETkLBDzQnZBPSAeBMClpJGlnJ5Fw=\ngithub.com/database64128/tfo-go/v2 v2.3.2/go.mod h1:GC3uB5oa4beGpCUbRb2ZOWP73bJJFmMyAVgQSO7r724=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa h1:h8TfIT1xc8FWbwwpmHn1J5i43Y0uZP97GqasGCzSRJk=\ngithub.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa/go.mod h1:Nx87SkVqTKd8UtT+xu7sM/l+LgXs6c0aHrlKusR+2EQ=\ngithub.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=\ngithub.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=\ngithub.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=\ngithub.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/florianl/go-nfqueue/v2 v2.0.2 h1:FL5lQTeetgpCvac1TRwSfgaXUn0YSO7WzGvWNIp3JPE=\ngithub.com/florianl/go-nfqueue/v2 v2.0.2/go.mod h1:VA09+iPOT43OMoCKNfXHyzujQUty2xmzyCRkBOlmabc=\ngithub.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=\ngithub.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=\ngithub.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=\ngithub.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=\ngithub.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=\ngithub.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=\ngithub.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=\ngithub.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=\ngithub.com/gaissmai/bart v0.18.0 h1:jQLBT/RduJu0pv/tLwXE+xKPgtWJejbxuXAR+wLJafo=\ngithub.com/gaissmai/bart v0.18.0/go.mod h1:JJzMAhNF5Rjo4SF4jWBrANuJfqY+FvsFhW7t1UZJ+XY=\ngithub.com/gin-contrib/gzip v1.2.5 h1:fIZs0S+l17pIu1P5XRJOo/YNqfIuPCrZZ3TWB7pjckI=\ngithub.com/gin-contrib/gzip v1.2.5/go.mod h1:aomRgR7ftdZV3uWY0gW/m8rChfxau0n8YVvwlOHONzw=\ngithub.com/gin-contrib/sessions v1.0.4 h1:ha6CNdpYiTOK/hTp05miJLbpTSNfOnFg5Jm2kbcqy8U=\ngithub.com/gin-contrib/sessions v1.0.4/go.mod h1:ccmkrb2z6iU2osiAHZG3x3J4suJK+OU27oqzlWOqQgs=\ngithub.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=\ngithub.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=\ngithub.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=\ngithub.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=\ngithub.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=\ngithub.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=\ngithub.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=\ngithub.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo=\ngithub.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=\ngithub.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=\ngithub.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=\ngithub.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=\ngithub.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=\ngithub.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=\ngithub.com/go-json-experiment/json v0.0.0-20250813024750-ebf49471dced h1:Q311OHjMh/u5E2TITc++WlTP5We0xNseRMkHDyvhW7I=\ngithub.com/go-json-experiment/json v0.0.0-20250813024750-ebf49471dced/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=\ngithub.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=\ngithub.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=\ngithub.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=\ngithub.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=\ngithub.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=\ngithub.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=\ngithub.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=\ngithub.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=\ngithub.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=\ngithub.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=\ngithub.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=\ngithub.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=\ngithub.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=\ngithub.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=\ngithub.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=\ngithub.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=\ngithub.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=\ngithub.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=\ngithub.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=\ngithub.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=\ngithub.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=\ngithub.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=\ngithub.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=\ngithub.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=\ngithub.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=\ngithub.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=\ngithub.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806 h1:wG8RYIyctLhdFk6Vl1yPGtSRtwGpVkWyZww1OCil2MI=\ngithub.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806/go.mod h1:Beg6V6zZ3oEn0JuiUQ4wqwuyqqzasOltcoXPtgLbFp4=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=\ngithub.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=\ngithub.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=\ngithub.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=\ngithub.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=\ngithub.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=\ngithub.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=\ngithub.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=\ngithub.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU=\ngithub.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo=\ngithub.com/insomniacslk/dhcp v0.0.0-20260220084031-5adc3eb26f91 h1:u9i04mGE3iliBh0EFuWaKsmcwrLacqGmq1G3XoaM7gY=\ngithub.com/insomniacslk/dhcp v0.0.0-20260220084031-5adc3eb26f91/go.mod h1:qfvBmyDNp+/liLEYWRvqny/PEz9hGe2Dz833eXILSmo=\ngithub.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=\ngithub.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=\ngithub.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=\ngithub.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=\ngithub.com/jsimonetti/rtnetlink v1.4.0 h1:Z1BF0fRgcETPEa0Kt0MRk3yV5+kF1FWTni6KUFKrq2I=\ngithub.com/jsimonetti/rtnetlink v1.4.0/go.mod h1:5W1jDvWdnthFJ7fxYX1GMK07BUpI4oskfOqvPteYS6E=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU=\ngithub.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=\ngithub.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=\ngithub.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=\ngithub.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=\ngithub.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=\ngithub.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=\ngithub.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=\ngithub.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk=\ngithub.com/letsencrypt/pebble/v2 v2.10.0 h1:Wq6gYXlsY6ubqI3hhxsTzdyotvfdjFBxuwYqCLCnj/U=\ngithub.com/letsencrypt/pebble/v2 v2.10.0/go.mod h1:Sk8cmUIPcIdv2nINo+9PB4L+ZBhzY+F9A1a/h/xmWiQ=\ngithub.com/libdns/acmedns v0.5.0 h1:5pRtmUj4Lb/QkNJSl1xgOGBUJTWW7RjpNaIhjpDXjPE=\ngithub.com/libdns/acmedns v0.5.0/go.mod h1:X7UAFP1Ep9NpTwWpVlrZzJLR7epynAy0wrIxSPFgKjQ=\ngithub.com/libdns/alidns v1.0.6 h1:/Ii428ty6WHFJmE24rZxq2taq++gh7rf9jhgLfp8PmM=\ngithub.com/libdns/alidns v1.0.6/go.mod h1:RECwyQ88e9VqQVtSrvX76o1ux3gQUKGzMgxICi+u7Ec=\ngithub.com/libdns/cloudflare v0.2.2 h1:XWHv+C1dDcApqazlh08Q6pjytYLgR2a+Y3xrXFu0vsI=\ngithub.com/libdns/cloudflare v0.2.2/go.mod h1:w9uTmRCDlAoafAsTPnn2nJ0XHK/eaUMh86DUk8BWi60=\ngithub.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=\ngithub.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=\ngithub.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8=\ngithub.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=\ngithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc=\ngithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=\ngithub.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/mattn/go-sqlite3 v1.14.30 h1:bVreufq3EAIG1Quvws73du3/QgdeZ3myglJlrzSYYCY=\ngithub.com/mattn/go-sqlite3 v1.14.30/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=\ngithub.com/mdlayher/netlink v1.9.0 h1:G8+GLq2x3v4D4MVIqDdNUhTUC7TKiCy/6MDkmItfKco=\ngithub.com/mdlayher/netlink v1.9.0/go.mod h1:YBnl5BXsCoRuwBjKKlZ+aYmEoq0r12FDA/3JC+94KDg=\ngithub.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=\ngithub.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=\ngithub.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg=\ngithub.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=\ngithub.com/mholt/acmez/v3 v3.1.6 h1:eGVQNObP0pBN4sxqrXeg7MYqTOWyoiYpQqITVWlrevk=\ngithub.com/mholt/acmez/v3 v3.1.6/go.mod h1:5nTPosTGosLxF3+LU4ygbgMRFDhbAVpqMI4+a4aHLBY=\ngithub.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=\ngithub.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=\ngithub.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=\ngithub.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=\ngithub.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=\ngithub.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=\ngithub.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=\ngithub.com/openai/openai-go/v3 v3.24.0 h1:08x6GnYiB+AAejTo6yzPY8RkZMJQ8NpreiOyM5QfyYU=\ngithub.com/openai/openai-go/v3 v3.24.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo=\ngithub.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=\ngithub.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=\ngithub.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=\ngithub.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=\ngithub.com/pires/go-proxyproto v0.8.1 h1:9KEixbdJfhrbtjpz/ZwCdWDD2Xem0NZ38qMYaASJgp0=\ngithub.com/pires/go-proxyproto v0.8.1/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus-community/pro-bing v0.4.0 h1:YMbv+i08gQz97OZZBwLyvmmQEEzyfyrrjEaAchdy3R4=\ngithub.com/prometheus-community/pro-bing v0.4.0/go.mod h1:b7wRYZtCcPmt4Sz319BykUU241rWLe1VFXyiyWK/dH4=\ngithub.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=\ngithub.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=\ngithub.com/quic-go/quic-go v0.57.1 h1:25KAAR9QR8KZrCZRThWMKVAwGoiHIrNbT72ULHTuI10=\ngithub.com/quic-go/quic-go v0.57.1/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s=\ngithub.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=\ngithub.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=\ngithub.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs=\ngithub.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a h1:+NkI2670SQpQWvkkD2QgdTuzQG263YZ+2emfpeyGqW0=\ngithub.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a/go.mod h1:63s7jpZqcDAIpj8oI/1v4Izok+npJOHACFCU6+huCkM=\ngithub.com/sagernet/cors v1.2.1 h1:Cv5Z8y9YSD6Gm+qSpNrL3LO4lD3eQVvbFYJSG7JCMHQ=\ngithub.com/sagernet/cors v1.2.1/go.mod h1:O64VyOjjhrkLmQIjF4KGRrJO/5dVXFdpEmCW/eISRAI=\ngithub.com/sagernet/cronet-go v0.0.0-20260303101018-cba7b9ac0399 h1:x3tVYQHdqqnKbEd9/H4KIGhtHTjA+KfiiaXedI3/w8Q=\ngithub.com/sagernet/cronet-go v0.0.0-20260303101018-cba7b9ac0399/go.mod h1:hwFHBEjjthyEquDULbr4c4ucMedp8Drb6Jvm2kt/0Bw=\ngithub.com/sagernet/cronet-go/all v0.0.0-20260303101018-cba7b9ac0399 h1:mD3ehudpYf1IFgCTv25d/B6KnBc/lLFq1jmSQIK24y0=\ngithub.com/sagernet/cronet-go/all v0.0.0-20260303101018-cba7b9ac0399/go.mod h1:MbYagcGGIaRo9tNrgafbCTO+Qc7eVEh32ZWMprSB8b0=\ngithub.com/sagernet/cronet-go/lib/android_386 v0.0.0-20260303100323-125d0d93b3e6 h1:ghRKgSaswefPwQF8AYtUlNyumILOB0ptJWxgZ8MFrEE=\ngithub.com/sagernet/cronet-go/lib/android_386 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:XXDwdjX/T8xftoeJxQmbBoYXZp8MAPFR2CwbFuTpEtw=\ngithub.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20260303100323-125d0d93b3e6 h1:Behr7YCnQP2dsvzAJDIoMd5nTVU9/d6MMtk/S3MctwA=\ngithub.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:iNiUGoLtnr8/JTuVNj7XJbmpOAp2C6+B81KDrPxwaZM=\ngithub.com/sagernet/cronet-go/lib/android_arm v0.0.0-20260303100323-125d0d93b3e6 h1:6UL9XdGU/44oTHj36e+EBDJ0RonFoObmd299NG/qQCU=\ngithub.com/sagernet/cronet-go/lib/android_arm v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:19ILNUOGIzRdOqa2mq+iY0JoHxuieB7/lnjYeaA2vEc=\ngithub.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:Q9apxjtkj6iMIBQlTo71QsOTrNlhHneaXQb1Q0IshU8=\ngithub.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:JxzGyQf94Cr6sBShKqODGDyRUlESfJK/Njcz9Lz6qMQ=\ngithub.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20260303100323-125d0d93b3e6 h1:0N+xlnMkFEeqgFe3X/PEvHt+/t+BPgxmbx7wzNcYppg=\ngithub.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:KN+9T9TBycGOLzmKU4QdcHAJEj6Nlx48ifnlTvvHMvs=\ngithub.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:7f2vTXtePikBSV1bdD0zs5/WuZM+bRuej3mREpWL/qQ=\ngithub.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:kojvtUc29KKnk8hs2QIANynVR59921SnGWA9kXohHc0=\ngithub.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6 h1:HMlnhEYs+axOa0tAJ79se3QsYB8CpRCQo9mewWWFeeg=\ngithub.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:hkQzRE5GDbaH1/ioqYh0Taho4L6i0yLRCVEZ5xHz5M0=\ngithub.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:Ux/U6vF+1AoGLSJK3jVa9Kqkn64MX4Ivv7fy0ikDrpQ=\ngithub.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:tzVJFTOm66UxLxy6K0ZN5Ic2PC79e+sKKnt+V9puEa4=\ngithub.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6 h1:5Dhuere2bQFzfGvKxA7TFgA5MoTtgcZMmJQuKwQKlyA=\ngithub.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:M/pN6m3j0HFU6/y83n0HU6GLYys3tYdr/xTE8hVEGMo=\ngithub.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20260303100323-125d0d93b3e6 h1:aMRcLow4UpZWZ28fR9FjveTL/4okrigZySIkEVZnlgA=\ngithub.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:cGh5hO6eljCo6KMQ/Cel8Xgq4+etL0awZLRBDVG1EZQ=\ngithub.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20260303100323-125d0d93b3e6 h1:y4g8oNtEfSdcKrBKsH5vMAjzGthvhHFNU80sanYDQEM=\ngithub.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:JFE0/cxaKkx0wqPMZU7MgaplQlU0zudv82dROJjClKU=\ngithub.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20260303100323-125d0d93b3e6 h1:CXN6OPILi5trwffmYiiJ9rqJL3XAWx1menLrBBwA0gU=\ngithub.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:vU8VftFeSt7fURCa3JXD6+k6ss1YAX+idQjPvHmJ2tI=\ngithub.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20260303100323-125d0d93b3e6 h1:ZphFHQeFOTpqCWPwFcQRnrePXajml8LbKlYFJ5n0isU=\ngithub.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:vCe4OUuL+XOUge9v3MyTD45BnuAXiH+DkjN9quDXJzQ=\ngithub.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20260303100323-125d0d93b3e6 h1:nKzFK84oANHz7I6bab+25bBY+pdpAbO0b3NJroyLldo=\ngithub.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:w9amBWrvjtohQzBGCKJ7LCh22LhTIJs4sE7cYaKQzM0=\ngithub.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:HqqZUGRXcWvvwlbuvjk/efo8TKW1H/aHdqQTde+Xs9Q=\ngithub.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:TqlsFtcYS/etTeck46kHBeT8Le0Igw1Q/AV88UnMS3s=\ngithub.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20260303100323-125d0d93b3e6 h1:D2v9lZZG5sm4x/CkG7uqc6ZU3YlhFQ+GmJfvZMK0h/s=\ngithub.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:B6Qd0vys8sv9OKVRN6J9RqDzYRGE938Fb2zrYdBDyTQ=\ngithub.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20260303100323-125d0d93b3e6 h1:TWveNeXHrA5r8XOlf+vw7U2b2M0ip6GNF89jcUi1ogw=\ngithub.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:3tXMMFY7AHugOVBZ5Al7cL7JKsnFOe5bMVr0hZPk3ow=\ngithub.com/sagernet/cronet-go/lib/linux_loong64 v0.0.0-20260303100323-125d0d93b3e6 h1:DVCBoXOZI4PNG0cbCLg8lrphRXoLFcAIDLNmzsCVg3I=\ngithub.com/sagernet/cronet-go/lib/linux_loong64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:Wt5uFdU3tnmm8YzobYewwdF7Mt6SucRQg6xeTNWC3Tk=\ngithub.com/sagernet/cronet-go/lib/linux_loong64_musl v0.0.0-20260303100323-125d0d93b3e6 h1:7s5xqNlBUWkIXdruPYi3/txXekQhGWxrYxbnB0cnARo=\ngithub.com/sagernet/cronet-go/lib/linux_loong64_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:lyIF6wKBLwWa5ZXaAKbAoewewl+yCHo2iYev39Mbj4E=\ngithub.com/sagernet/cronet-go/lib/linux_mips64le v0.0.0-20260303100323-125d0d93b3e6 h1:eyEb+Q7VH4hpE1nV+EmEnN2XX5WilgBpIsfCw4C/7no=\ngithub.com/sagernet/cronet-go/lib/linux_mips64le v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:H46PnSTTZNcZokLLiDeMDaHiS1l14PH3tzWi0eykjD8=\ngithub.com/sagernet/cronet-go/lib/linux_mipsle v0.0.0-20260303100323-125d0d93b3e6 h1:9F1W7+z1hHST6GSzdpQ8Q0NCkneAL18dkRA1HfxH09A=\ngithub.com/sagernet/cronet-go/lib/linux_mipsle v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:RBhSUDAKWq7fswtV4nQUQhuaTLcX3ettR7teA7/yf2w=\ngithub.com/sagernet/cronet-go/lib/linux_mipsle_musl v0.0.0-20260303100323-125d0d93b3e6 h1:MmQIR3iJsdvw1ONBP3geK57i9c3+v9dXPMNdZYcYGKw=\ngithub.com/sagernet/cronet-go/lib/linux_mipsle_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:wRzoIOGG4xbpp3Gh3triLKwMwYriScXzFtunLYhY4w0=\ngithub.com/sagernet/cronet-go/lib/linux_riscv64 v0.0.0-20260303100323-125d0d93b3e6 h1:j6Pk1Wsl+PCbKRXtp7a912D2D6zqX5Nk51wDQU9TEDc=\ngithub.com/sagernet/cronet-go/lib/linux_riscv64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:LNiZXmWil1OPwKCheqQjtakZlJuKGFz+iv2eGF76Hhs=\ngithub.com/sagernet/cronet-go/lib/linux_riscv64_musl v0.0.0-20260303100323-125d0d93b3e6 h1:0DnFhbRfNqwguNCxiinA7BowQ/RaFt627sjW09JNp80=\ngithub.com/sagernet/cronet-go/lib/linux_riscv64_musl v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:YFDGKTkpkJGc5+hnX/RYosZyTWg9h+68VB55fYRRLYc=\ngithub.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6 h1:3CZmlEk2/WW5UHLFJZxXPJ9IJxX3td8U3PyqWSGMl3c=\ngithub.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:aaX0YGl8nhGmfRWI8bc3BtDjY8Vzx6O0cS/e1uqxDq4=\ngithub.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:eHkVRptoZf3BuuskkjcclO2dwQrX4zluoVGODMrX7n0=\ngithub.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:EdzMKA96xITc42QEI+ct4SwqX8Dn3ltKK8wzdkLWpSc=\ngithub.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6 h1:UgFmE0cZo9euu8/7sTAhj1G8lldavwXBdcPNyTE29CQ=\ngithub.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:qix4kv1TTAJ5tY4lJ9vjhe9EY4mM+B7H5giOhbxDVcc=\ngithub.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20260303100323-125d0d93b3e6 h1:xbg3ZB9tLMGDQe4+aewG0Z4bEP/2pLtYBcDzILv5eEc=\ngithub.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:lm9w/oCCRyBiUa3G8lDQTT8x/ONUvgVR2iV9fVzUZB8=\ngithub.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20260303100323-125d0d93b3e6 h1:M0bTSTSTnSMlPY2WaZT6fL5TFICqk8v4cm+QVf8Fcao=\ngithub.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20260303100323-125d0d93b3e6/go.mod h1:n34YyLgapgjWdKa0IoeczjAFCwD3/dxbsH5sucKw0bw=\ngithub.com/sagernet/fswatch v0.1.1 h1:YqID+93B7VRfqIH3PArW/XpJv5H4OLEVWDfProGoRQs=\ngithub.com/sagernet/fswatch v0.1.1/go.mod h1:nz85laH0mkQqJfaOrqPpkwtU1znMFNVTpT/5oRsVz/o=\ngithub.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1 h1:AzCE2RhBjLJ4WIWc/GejpNh+z30d5H1hwaB0nD9eY3o=\ngithub.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1/go.mod h1:NJKBtm9nVEK3iyOYWsUlrDQuoGh4zJ4KOPhSYVidvQ4=\ngithub.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=\ngithub.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=\ngithub.com/sagernet/nftables v0.3.0-beta.4 h1:kbULlAwAC3jvdGAC1P5Fa3GSxVwQJibNenDW2zaXr8I=\ngithub.com/sagernet/nftables v0.3.0-beta.4/go.mod h1:OQXAjvjNGGFxaTgVCSTRIhYB5/llyVDeapVoENYBDS8=\ngithub.com/sagernet/quic-go v0.59.0-sing-box-mod.4 h1:6qvrUW79S+CrPwWz6cMePXohgjHoKxLo3c+MDhNwc3o=\ngithub.com/sagernet/quic-go v0.59.0-sing-box-mod.4/go.mod h1:OqILvS182CyOol5zNNo6bguvOGgXzV459+chpRaUC+4=\ngithub.com/sagernet/sing v0.8.2 h1:kX1IH9SWJv4S0T9M8O+HNahWgbOuY1VauxbF7NU5lOg=\ngithub.com/sagernet/sing v0.8.2/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=\ngithub.com/sagernet/sing-box v1.13.2 h1:wChNq1BIqr5YKjGMWNWwmXSfEBaKk4q76WD2TH8tpRs=\ngithub.com/sagernet/sing-box v1.13.2/go.mod h1:KdOFknh0k/LSGlWPwc6A2+KqnRyI7gliIRoxPxMM5Dw=\ngithub.com/sagernet/sing-mux v0.3.4 h1:ZQplKl8MNXutjzbMVtWvWG31fohhgOfCuUZR4dVQ8+s=\ngithub.com/sagernet/sing-mux v0.3.4/go.mod h1:QvlKMyNBNrQoyX4x+gq028uPbLM2XeRpWtDsWBJbFSk=\ngithub.com/sagernet/sing-quic v0.6.0 h1:dhrFnP45wgVKEOT1EvtsToxdzRnHIDIAgj6WHV9pLyM=\ngithub.com/sagernet/sing-quic v0.6.0/go.mod h1:K5bWvITOm4vE10fwLfrWpw27bCoVJ+tfQ79tOWg+Ko8=\ngithub.com/sagernet/sing-shadowsocks v0.2.8 h1:PURj5PRoAkqeHh2ZW205RWzN9E9RtKCVCzByXruQWfE=\ngithub.com/sagernet/sing-shadowsocks v0.2.8/go.mod h1:lo7TWEMDcN5/h5B8S0ew+r78ZODn6SwVaFhvB6H+PTI=\ngithub.com/sagernet/sing-shadowsocks2 v0.2.1 h1:dWV9OXCeFPuYGHb6IRqlSptVnSzOelnqqs2gQ2/Qioo=\ngithub.com/sagernet/sing-shadowsocks2 v0.2.1/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=\ngithub.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11 h1:tK+75l64tm9WvEFrYRE1t0YxoFdWQqw/h7Uhzj0vJ+w=\ngithub.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11/go.mod h1:sWqKnGlMipCHaGsw1sTTlimyUpgzP4WP3pjhCsYt9oA=\ngithub.com/sagernet/sing-tun v0.8.2 h1:rQr/x3eQCHh3oleIaoJdPdJwqzZp4+QWcJLT0Wz2xKY=\ngithub.com/sagernet/sing-tun v0.8.2/go.mod h1:pLCo4o+LacXEzz0bhwhJkKBjLlKOGPBNOAZ97ZVZWzs=\ngithub.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1 h1:aSwUNYUkVyVvdmBSufR8/nRFonwJeKSIROxHcm5br9o=\ngithub.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1/go.mod h1:P11scgTxMxVVQ8dlM27yNm3Cro40mD0+gHbnqrNGDuY=\ngithub.com/sagernet/smux v1.5.50-sing-box-mod.1 h1:XkJcivBC9V4wBjiGXIXZ229aZCU1hzcbp6kSkkyQ478=\ngithub.com/sagernet/smux v1.5.50-sing-box-mod.1/go.mod h1:NjhsCEWedJm7eFLyhuBgIEzwfhRmytrUoiLluxs5Sk8=\ngithub.com/sagernet/tailscale v1.92.4-sing-box-1.13-mod.6.0.20260303140313-3bcf9a4b9349 h1:ju7aTbndj2sqK4NplE97ynLdhuCtel5OS4e0NrT71nk=\ngithub.com/sagernet/tailscale v1.92.4-sing-box-1.13-mod.6.0.20260303140313-3bcf9a4b9349/go.mod h1:m87GAn4UcesHQF3leaPFEINZETO5za1LGn1GJdNDgNc=\ngithub.com/sagernet/wireguard-go v0.0.2-beta.1.0.20260224074747-506b7631853c h1:f9cXNB+IOOPnR8DOLMTpr42jf7naxh5Un5Y09BBf5Cg=\ngithub.com/sagernet/wireguard-go v0.0.2-beta.1.0.20260224074747-506b7631853c/go.mod h1:WUxgxUDZoCF2sxVmW+STSxatP02Qn3FcafTiI2BLtE0=\ngithub.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 h1:6uUiZcDRnZSAegryaUGwPC/Fj13JSHwiTftrXhMmYOc=\ngithub.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854/go.mod h1:LtfoSK3+NG57tvnVEHgcuBW9ujgE8enPSgzgwStwCAA=\ngithub.com/shirou/gopsutil/v4 v4.26.1 h1:TOkEyriIXk2HX9d4isZJtbjXbEjf5qyKPAzbzY0JWSo=\ngithub.com/shirou/gopsutil/v4 v4.26.1/go.mod h1:medLI9/UNAb0dOI9Q3/7yWSqKkj00u+1tgY8nvv41pc=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=\ngithub.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=\ngithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tailscale/certstore v0.1.1-0.20231202035212-d3fa0460f47e h1:PtWT87weP5LWHEY//SWsYkSO3RWRZo4OSWagh3YD2vQ=\ngithub.com/tailscale/certstore v0.1.1-0.20231202035212-d3fa0460f47e/go.mod h1:XrBNfAFN+pwoWuksbFS9Ccxnopa15zJGgXRFN90l3K4=\ngithub.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4=\ngithub.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55/go.mod h1:4k4QO+dQ3R5FofL+SanAUZe+/QfeK0+OIuwDIRu2vSg=\ngithub.com/tailscale/goupnp v1.0.1-0.20210804011211-c64d0f06ea05 h1:4chzWmimtJPxRs2O36yuGRW3f9SYV+bMTTvMBI0EKio=\ngithub.com/tailscale/goupnp v1.0.1-0.20210804011211-c64d0f06ea05/go.mod h1:PdCqy9JzfWMJf1H5UJW2ip33/d4YkoKN0r67yKH1mG8=\ngithub.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a h1:SJy1Pu0eH1C29XwJucQo73FrleVK6t4kYz4NVhp34Yw=\ngithub.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a/go.mod h1:DFSS3NAGHthKo1gTlmEcSBiZrRJXi28rLNd/1udP1c8=\ngithub.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7 h1:uFsXVBE9Qr4ZoF094vE6iYTLDl0qCiKzYXlL6UeWObU=\ngithub.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7/go.mod h1:NzVQi3Mleb+qzq8VmcWpSkcSYxXIg0DkI6XDzpVkhJ0=\ngithub.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+yfntqhI3oAu9i27nEojcQ4NuBQOo5ZFA=\ngithub.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc=\ngithub.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976 h1:UBPHPtv8+nEAy2PD8RyAhOYvau1ek0HDJqLS/Pysi14=\ngithub.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976/go.mod h1:agQPE6y6ldqCOui2gkIh7ZMztTkIQKH049tv8siLuNQ=\ngithub.com/tc-hib/winres v0.2.1 h1:YDE0FiP0VmtRaDn7+aaChp1KiF4owBiJa5l964l5ujA=\ngithub.com/tc-hib/winres v0.2.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk=\ngithub.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=\ngithub.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=\ngithub.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=\ngithub.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=\ngithub.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=\ngithub.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=\ngithub.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=\ngithub.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=\ngithub.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=\ngithub.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=\ngithub.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=\ngithub.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 h1:pyC9PaHYZFgEKFdlp3G8RaCKgVpHZnecvArXvPXcFkM=\ngithub.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701/go.mod h1:P3a5rG4X7tI17Nn3aOIAYr5HbIMukwXG0urG0WuL8OA=\ngithub.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=\ngithub.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=\ngithub.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=\ngithub.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=\ngithub.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=\ngithub.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=\ngithub.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=\ngithub.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=\ngithub.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngithub.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=\ngithub.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=\ngithub.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=\ngithub.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=\ngithub.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=\ngithub.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=\ngo.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=\ngo.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=\ngo.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=\ngo.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=\ngo.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=\ngo.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=\ngo.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=\ngo.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=\ngo4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek=\ngo4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=\ngo4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=\ngo4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=\ngolang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=\ngolang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=\ngolang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 h1:fQsdNF2N+/YewlRZiricy4P1iimyPKZ/xwniHj8Q2a0=\ngolang.org/x/exp v0.0.0-20251219203646-944ab1f22d93/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=\ngolang.org/x/image v0.27.0 h1:C8gA4oWU/tKkdCfYT6T2u4faJu3MeNS5O8UPWlPF61w=\ngolang.org/x/image v0.27.0/go.mod h1:xbdrClrAUway1MUTEZDq9mz/UpRwYAkFFNUslZtcB+g=\ngolang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=\ngolang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=\ngolang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=\ngolang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=\ngolang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=\ngolang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=\ngolang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=\ngolang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngolang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=\ngolang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=\ngolang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=\ngolang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=\ngolang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=\ngolang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10 h1:3GDAcqdIg1ozBNLgPy4SLT84nfcBjr6rhGtXYtrkWLU=\ngolang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10/go.mod h1:T97yPqesLiNrOYxkwmhMI0ZIlJDm+p0PMR8eRVeR5tQ=\ngolang.zx2c4.com/wireguard/windows v0.5.3 h1:On6j2Rpn3OEMXqBq00QEDC7bWSZrPIHKIus8eIuExIE=\ngolang.zx2c4.com/wireguard/windows v0.5.3/go.mod h1:9TEe8TJmtwyQebdFwAkEWOPr3prrtqm+REGFifP60hI=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=\ngoogle.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=\ngoogle.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=\ngopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=\ngorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=\ngorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=\ngorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=\nlukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=\nlukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=\nsoftware.sslmate.com/src/go-pkcs12 v0.4.0 h1:H2g08FrTvSFKUj+D309j1DPfk5APnIdAQAB8aEykJ5k=\nsoftware.sslmate.com/src/go-pkcs12 v0.4.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=\n"
  },
  {
    "path": "install.sh",
    "content": "#!/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[[ $EUID -ne 0 ]] && echo -e \"${red}Fatal error: ${plain} Please run this script with root privilege \\n \" && exit 1\n\n# Check OS and set release variable\nif [[ -f /etc/os-release ]]; then\n    source /etc/os-release\n    release=$ID\nelif [[ -f /usr/lib/os-release ]]; then\n    source /usr/lib/os-release\n    release=$ID\nelse\n    echo \"Failed to check the system OS, please contact the author!\" >&2\n    exit 1\nfi\necho \"The OS release is: $release\"\n\narch() {\n    case \"$(uname -m)\" in\n    x86_64 | x64 | amd64) echo 'amd64' ;;\n    i*86 | x86) echo '386' ;;\n    armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;\n    armv7* | armv7 | arm) echo 'armv7' ;;\n    armv6* | armv6) echo 'armv6' ;;\n    armv5* | armv5) echo 'armv5' ;;\n    s390x) echo 's390x' ;;\n    *) echo -e \"${green}Unsupported CPU architecture! ${plain}\" && rm -f install.sh && exit 1 ;;\n    esac\n}\n\necho \"arch: $(arch)\"\n\ninstall_base() {\n    case \"${release}\" in\n    centos | almalinux | rocky | oracle)\n        yum -y update && yum install -y -q wget curl tar tzdata\n        ;;\n    fedora)\n        dnf -y update && dnf install -y -q wget curl tar tzdata\n        ;;\n    arch | manjaro | parch)\n        pacman -Syu && pacman -Syu --noconfirm wget curl tar tzdata\n        ;;\n    opensuse-tumbleweed)\n        zypper refresh && zypper -q install -y wget curl tar timezone\n        ;;\n    *)\n        apt-get update && apt-get install -y -q wget curl tar tzdata\n        ;;\n    esac\n}\n\nconfig_after_install() {\n    echo -e \"${yellow}Migration... ${plain}\"\n    /usr/local/s-ui/sui migrate\n    \n    echo -e \"${yellow}Install/update finished! For security it's recommended to modify panel settings ${plain}\"\n    read -p \"Do you want to continue with the modification [y/n]? \": config_confirm\n    if [[ \"${config_confirm}\" == \"y\" || \"${config_confirm}\" == \"Y\" ]]; then\n        echo -e \"Enter the ${yellow}panel port${plain} (leave blank for existing/default value):\"\n        read config_port\n        echo -e \"Enter the ${yellow}panel path${plain} (leave blank for existing/default value):\"\n        read config_path\n\n        # Sub configuration\n        echo -e \"Enter the ${yellow}subscription port${plain} (leave blank for existing/default value):\"\n        read config_subPort\n        echo -e \"Enter the ${yellow}subscription path${plain} (leave blank for existing/default value):\" \n        read config_subPath\n\n        # Set configs\n        echo -e \"${yellow}Initializing, please wait...${plain}\"\n        params=\"\"\n        [ -z \"$config_port\" ] || params=\"$params -port $config_port\"\n        [ -z \"$config_path\" ] || params=\"$params -path $config_path\"\n        [ -z \"$config_subPort\" ] || params=\"$params -subPort $config_subPort\"\n        [ -z \"$config_subPath\" ] || params=\"$params -subPath $config_subPath\"\n        /usr/local/s-ui/sui setting ${params}\n\n        read -p \"Do you want to change admin credentials [y/n]? \": admin_confirm\n        if [[ \"${admin_confirm}\" == \"y\" || \"${admin_confirm}\" == \"Y\" ]]; then\n            # First admin credentials\n            read -p \"Please set up your username:\" config_account\n            read -p \"Please set up your password:\" config_password\n\n            # Set credentials\n            echo -e \"${yellow}Initializing, please wait...${plain}\"\n            /usr/local/s-ui/sui admin -username ${config_account} -password ${config_password}\n        else\n            echo -e \"${yellow}Your current admin credentials: ${plain}\"\n            /usr/local/s-ui/sui admin -show\n        fi\n    else\n        echo -e \"${red}cancel...${plain}\"\n        if [[ ! -f \"/usr/local/s-ui/db/s-ui.db\" ]]; then\n            local usernameTemp=$(head -c 6 /dev/urandom | base64)\n            local passwordTemp=$(head -c 6 /dev/urandom | base64)\n            echo -e \"this is a fresh installation,will generate random login info for security concerns:\"\n            echo -e \"###############################################\"\n            echo -e \"${green}username:${usernameTemp}${plain}\"\n            echo -e \"${green}password:${passwordTemp}${plain}\"\n            echo -e \"###############################################\"\n            echo -e \"${red}if you forgot your login info,you can type ${green}s-ui${red} for configuration menu${plain}\"\n            /usr/local/s-ui/sui admin -username ${usernameTemp} -password ${passwordTemp}\n        else\n            echo -e \"${red} this is your upgrade,will keep old settings,if you forgot your login info,you can type ${green}s-ui${red} for configuration menu${plain}\"\n        fi\n    fi\n}\n\nprepare_services() {\n    if [[ -f \"/etc/systemd/system/sing-box.service\" ]]; then\n        echo -e \"${yellow}Stopping sing-box service... ${plain}\"\n        systemctl stop sing-box\n        rm -f /usr/local/s-ui/bin/sing-box /usr/local/s-ui/bin/runSingbox.sh /usr/local/s-ui/bin/signal\n    fi\n    if [[ -e \"/usr/local/s-ui/bin\" ]]; then\n        echo -e \"###############################################################\"\n        echo -e \"${green}/usr/local/s-ui/bin${red} directory exists yet!\"\n        echo -e \"Please check the content and delete it manually after migration ${plain}\"\n        echo -e \"###############################################################\"\n    fi\n    systemctl daemon-reload\n}\n\ninstall_s-ui() {\n    cd /tmp/\n\n    if [ $# == 0 ]; then\n        last_version=$(curl -Ls \"https://api.github.com/repos/alireza0/s-ui/releases/latest\" | grep '\"tag_name\":' | sed -E 's/.*\"([^\"]+)\".*/\\1/')\n        if [[ ! -n \"$last_version\" ]]; then\n            echo -e \"${red}Failed to fetch s-ui version, it maybe due to Github API restrictions, please try it later${plain}\"\n            exit 1\n        fi\n        echo -e \"Got s-ui latest version: ${last_version}, beginning the installation...\"\n        wget -N --no-check-certificate -O /tmp/s-ui-linux-$(arch).tar.gz https://github.com/alireza0/s-ui/releases/download/${last_version}/s-ui-linux-$(arch).tar.gz\n        if [[ $? -ne 0 ]]; then\n            echo -e \"${red}Downloading s-ui failed, please be sure that your server can access Github ${plain}\"\n            exit 1\n        fi\n    else\n        last_version=$1\n        url=\"https://github.com/alireza0/s-ui/releases/download/${last_version}/s-ui-linux-$(arch).tar.gz\"\n        echo -e \"Beginning the install s-ui v$1\"\n        wget -N --no-check-certificate -O /tmp/s-ui-linux-$(arch).tar.gz ${url}\n        if [[ $? -ne 0 ]]; then\n            echo -e \"${red}download s-ui v$1 failed,please check the version exists${plain}\"\n            exit 1\n        fi\n    fi\n\n    if [[ -e /usr/local/s-ui/ ]]; then\n        systemctl stop s-ui\n    fi\n\n    tar zxvf s-ui-linux-$(arch).tar.gz\n    rm s-ui-linux-$(arch).tar.gz -f\n\n    chmod +x s-ui/sui s-ui/s-ui.sh\n    cp s-ui/s-ui.sh /usr/bin/s-ui\n    cp -rf s-ui /usr/local/\n    cp -f s-ui/*.service /etc/systemd/system/\n    rm -rf s-ui\n\n    config_after_install\n    prepare_services\n\n    systemctl enable s-ui --now\n\n    echo -e \"${green}s-ui v${last_version}${plain} installation finished, it is up and running now...\"\n    echo -e \"You may access the Panel with following URL(s):${green}\"\n    /usr/local/s-ui/sui uri\n    echo -e \"${plain}\"\n    echo -e \"\"\n    s-ui help\n}\n\necho -e \"${green}Executing...${plain}\"\ninstall_base\ninstall_s-ui $1\n"
  },
  {
    "path": "logger/logger.go",
    "content": "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\tlogBuffer []struct {\n\t\ttime  string\n\t\tlevel logging.Level\n\t\tlog   string\n\t}\n)\n\nfunc InitLogger(level logging.Level) {\n\tnewLogger := logging.MustGetLogger(\"s-ui\")\n\tvar err error\n\tvar backend logging.Backend\n\tvar format logging.Formatter\n\n\t_, inContainer := os.LookupEnv(\"container\")\n\tif !inContainer {\n\t\tif _, statErr := os.Stat(\"/.dockerenv\"); statErr == nil {\n\t\t\tinContainer = true\n\t\t}\n\t}\n\tif inContainer {\n\t\tbackend = logging.NewLogBackend(os.Stderr, \"\", 0)\n\t\tformat = logging.MustStringFormatter(`%{time:2006/01/02 15:04:05} %{level} - %{message}`)\n\t} else {\n\t\tbackend, err = logging.NewSyslogBackend(\"\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Unable to use syslog: \" + err.Error())\n\t\t\tbackend = logging.NewLogBackend(os.Stderr, \"\", 0)\n\t\t}\n\t\tif err != nil {\n\t\t\tformat = logging.MustStringFormatter(`%{time:2006/01/02 15:04:05} %{level} - %{message}`)\n\t\t} else {\n\t\t\tformat = logging.MustStringFormatter(`%{level} - %{message}`)\n\t\t}\n\t}\n\n\tbackendFormatter := logging.NewBackendFormatter(backend, format)\n\tbackendLeveled := logging.AddModuleLevel(backendFormatter)\n\tbackendLeveled.SetLevel(level, \"s-ui\")\n\tnewLogger.SetBackend(backendLeveled)\n\n\tlogger = newLogger\n}\n\nfunc GetLogger() *logging.Logger {\n\treturn logger\n}\n\nfunc Debug(args ...interface{}) {\n\tlogger.Debug(args...)\n\taddToBuffer(\"DEBUG\", fmt.Sprint(args...))\n}\n\nfunc Debugf(format string, args ...interface{}) {\n\tlogger.Debugf(format, args...)\n\taddToBuffer(\"DEBUG\", fmt.Sprintf(format, args...))\n}\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n\taddToBuffer(\"INFO\", fmt.Sprint(args...))\n}\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n\taddToBuffer(\"INFO\", fmt.Sprintf(format, args...))\n}\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n\taddToBuffer(\"WARNING\", fmt.Sprint(args...))\n}\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n\taddToBuffer(\"WARNING\", fmt.Sprintf(format, args...))\n}\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n\taddToBuffer(\"ERROR\", fmt.Sprint(args...))\n}\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n\taddToBuffer(\"ERROR\", fmt.Sprintf(format, args...))\n}\n\nfunc addToBuffer(level string, newLog string) {\n\tt := time.Now()\n\tif len(logBuffer) >= 10240 {\n\t\tlogBuffer = logBuffer[1:]\n\t}\n\n\tlogLevel, _ := logging.LogLevel(level)\n\tlogBuffer = append(logBuffer, struct {\n\t\ttime  string\n\t\tlevel logging.Level\n\t\tlog   string\n\t}{\n\t\ttime:  t.Format(\"2006/01/02 15:04:05\"),\n\t\tlevel: logLevel,\n\t\tlog:   newLog,\n\t})\n}\n\nfunc GetLogs(c int, level string) []string {\n\tvar output []string\n\tlogLevel, _ := logging.LogLevel(level)\n\n\tfor i := len(logBuffer) - 1; i >= 0 && len(output) <= c; i-- {\n\t\tif logBuffer[i].level <= logLevel {\n\t\t\toutput = append(output, fmt.Sprintf(\"%s %s - %s\", logBuffer[i].time, logBuffer[i].level, logBuffer[i].log))\n\t\t}\n\t}\n\treturn output\n}\n"
  },
  {
    "path": "main.go",
    "content": "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/cmd\"\n)\n\nfunc runApp() {\n\tapp := app.NewApp()\n\n\terr := app.Init()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = app.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsigCh := make(chan os.Signal, 1)\n\t// Trap shutdown signals\n\tsignal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM)\n\tfor {\n\t\tsig := <-sigCh\n\n\t\tswitch sig {\n\t\tcase syscall.SIGHUP:\n\t\t\tapp.RestartApp()\n\t\tdefault:\n\t\t\tapp.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\trunApp()\n\t\treturn\n\t} else {\n\t\tcmd.ParseCmd()\n\t}\n}\n"
  },
  {
    "path": "middleware/domainValidator.go",
    "content": "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 string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\thost := c.Request.Host\n\t\tif colonIndex := strings.LastIndex(host, \":\"); colonIndex != -1 {\n\t\t\thost, _, _ = net.SplitHostPort(c.Request.Host)\n\t\t}\n\n\t\tif host != domain {\n\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "network/auto_https_conn.go",
    "content": "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\tfirstBuf []byte\n\tbufStart int\n\n\treadRequestOnce sync.Once\n}\n\nfunc NewAutoHttpsConn(conn net.Conn) net.Conn {\n\treturn &AutoHttpsConn{\n\t\tConn: conn,\n\t}\n}\n\nfunc (c *AutoHttpsConn) readRequest() bool {\n\tc.firstBuf = make([]byte, 2048)\n\tn, err := c.Conn.Read(c.firstBuf)\n\tc.firstBuf = c.firstBuf[:n]\n\tif err != nil {\n\t\treturn false\n\t}\n\treader := bytes.NewReader(c.firstBuf)\n\tbufReader := bufio.NewReader(reader)\n\trequest, err := http.ReadRequest(bufReader)\n\tif err != nil {\n\t\treturn false\n\t}\n\tresp := http.Response{\n\t\tHeader: http.Header{},\n\t}\n\tresp.StatusCode = http.StatusTemporaryRedirect\n\tlocation := fmt.Sprintf(\"https://%v%v\", request.Host, request.RequestURI)\n\tresp.Header.Set(\"Location\", location)\n\tresp.Write(c.Conn)\n\tc.Close()\n\tc.firstBuf = nil\n\treturn true\n}\n\nfunc (c *AutoHttpsConn) Read(buf []byte) (int, error) {\n\tc.readRequestOnce.Do(func() {\n\t\tc.readRequest()\n\t})\n\n\tif c.firstBuf != nil {\n\t\tn := copy(buf, c.firstBuf[c.bufStart:])\n\t\tc.bufStart += n\n\t\tif c.bufStart >= len(c.firstBuf) {\n\t\t\tc.firstBuf = nil\n\t\t}\n\t\treturn n, nil\n\t}\n\n\treturn c.Conn.Read(buf)\n}\n"
  },
  {
    "path": "network/auto_https_listener.go",
    "content": "package network\n\nimport \"net\"\n\ntype AutoHttpsListener struct {\n\tnet.Listener\n}\n\nfunc NewAutoHttpsListener(listener net.Listener) net.Listener {\n\treturn &AutoHttpsListener{\n\t\tListener: listener,\n\t}\n}\n\nfunc (l *AutoHttpsListener) Accept() (net.Conn, error) {\n\tconn, err := l.Listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewAutoHttpsConn(conn), nil\n}\n"
  },
  {
    "path": "runSUI.sh",
    "content": "./build.sh\nSUI_DB_FOLDER=\"db\" SUI_DEBUG=true ./sui"
  },
  {
    "path": "s-ui.service",
    "content": "[Unit]\nDescription=s-ui Service\nAfter=network.target\nWants=network.target\n\n[Service]\nType=simple\nWorkingDirectory=/usr/local/s-ui/\nExecStart=/usr/local/s-ui/sui\nRestart=on-failure\nRestartSec=10s\n\n[Install]\nWantedBy=multi-user.target"
  },
  {
    "path": "s-ui.sh",
    "content": "#!/bin/bash\n\nred='\\033[0;31m'\ngreen='\\033[0;32m'\nyellow='\\033[0;33m'\nplain='\\033[0m'\n\nfunction LOGD() {\n    echo -e \"${yellow}[DEG] $* ${plain}\"\n}\n\nfunction LOGE() {\n    echo -e \"${red}[ERR] $* ${plain}\"\n}\n\nfunction LOGI() {\n    echo -e \"${green}[INF] $* ${plain}\"\n}\n\n[[ $EUID -ne 0 ]] && LOGE \"ERROR: You must be root to run this script! \\n\" && exit 1\n\nif [[ -f /etc/os-release ]]; then\n    source /etc/os-release\n    release=$ID\nelif [[ -f /usr/lib/os-release ]]; then\n    source /usr/lib/os-release\n    release=$ID\nelse\n    echo \"Failed to check the system OS, please contact the author!\" >&2\n    exit 1\nfi\n\necho \"The OS release is: $release\"\n\nconfirm() {\n    if [[ $# > 1 ]]; then\n        echo && read -p \"$1 [Default$2]: \" temp\n        if [[ x\"${temp}\" == x\"\" ]]; then\n            temp=$2\n        fi\n    else\n        read -p \"$1 [y/n]: \" temp\n    fi\n    if [[ x\"${temp}\" == x\"y\" || x\"${temp}\" == x\"Y\" ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nconfirm_restart() {\n    confirm \"Restart the ${1} service\" \"y\"\n    if [[ $? == 0 ]]; then\n        restart\n    else\n        show_menu\n    fi\n}\n\nbefore_show_menu() {\n    echo && echo -n -e \"${yellow}Press enter to return to the main menu: ${plain}\" && read temp\n    show_menu\n}\n\ninstall() {\n    bash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/main/install.sh)\n    if [[ $? == 0 ]]; then\n        if [[ $# == 0 ]]; then\n            start\n        else\n            start 0\n        fi\n    fi\n}\n\nupdate() {\n    confirm \"This function will forcefully reinstall the latest version, and the data will not be lost. Do you want to continue?\" \"n\"\n    if [[ $? != 0 ]]; then\n        LOGE \"Cancelled\"\n        if [[ $# == 0 ]]; then\n            before_show_menu\n        fi\n        return 0\n    fi\n    bash <(curl -Ls https://raw.githubusercontent.com/alireza0/s-ui/main/install.sh)\n    if [[ $? == 0 ]]; then\n        LOGI \"Update is complete, Panel has automatically restarted \"\n        exit 0\n    fi\n}\n\ncustom_version() {\n    echo \"Enter the panel version (like 0.0.1):\"\n    read panel_version\n\n    if [ -z \"$panel_version\" ]; then\n        echo \"Panel version cannot be empty. Exiting.\"\n    exit 1\n    fi\n\n    download_link=\"https://raw.githubusercontent.com/alireza0/s-ui/master/install.sh\"\n\n    install_command=\"bash <(curl -Ls $download_link) $panel_version\"\n\n    echo \"Downloading and installing panel version $panel_version...\"\n    eval $install_command\n}\n\nuninstall() {\n    confirm \"Are you sure you want to uninstall the panel?\" \"n\"\n    if [[ $? != 0 ]]; then\n        if [[ $# == 0 ]]; then\n            show_menu\n        fi\n        return 0\n    fi\n    systemctl stop s-ui\n    systemctl disable s-ui\n    rm /etc/systemd/system/s-ui.service -f\n    systemctl daemon-reload\n    systemctl reset-failed\n    rm /etc/s-ui/ -rf\n    rm /usr/local/s-ui/ -rf\n\n    echo \"\"\n    echo -e \"Uninstalled Successfully, If you want to remove this script, then after exiting the script run ${green}rm /usr/local/s-ui -f${plain} to delete it.\"\n    echo \"\"\n\n    if [[ $# == 0 ]]; then\n        before_show_menu\n    fi\n}\n\nreset_admin() {\n    echo \"It is not recommended to set admin's credentials to default!\"\n    confirm \"Are you sure you want to reset admin's credentials to default ?\" \"n\"\n    if [[ $? == 0 ]]; then\n        /usr/local/s-ui/sui admin -reset\n    fi\n    before_show_menu\n}\n\nset_admin() {\n    echo \"It is not recommended to set admin's credentials to a complex text.\"\n    read -p \"Please set up your username:\" config_account\n    read -p \"Please set up your password:\" config_password\n    /usr/local/s-ui/sui admin -username ${config_account} -password ${config_password}\n    before_show_menu\n}\n\nview_admin() {\n    /usr/local/s-ui/sui admin -show\n    before_show_menu\n}\n\nreset_setting() {\n    confirm \"Are you sure you want to reset settings to default ?\" \"n\"\n    if [[ $? == 0 ]]; then\n        /usr/local/s-ui/sui setting -reset\n    fi\n    before_show_menu\n}\n\nset_setting() {\n    echo -e \"Enter the ${yellow}panel port${plain} (leave blank for existing/default value):\"\n    read config_port\n    echo -e \"Enter the ${yellow}panel path${plain} (leave blank for existing/default value):\"\n    read config_path\n\n    echo -e \"Enter the ${yellow}subscription port${plain} (leave blank for existing/default value):\"\n    read config_subPort\n    echo -e \"Enter the ${yellow}subscription path${plain} (leave blank for existing/default value):\" \n    read config_subPath\n\n    echo -e \"${yellow}Initializing, please wait...${plain}\"\n    params=\"\"\n    [ -z \"$config_port\" ] || params=\"$params -port $config_port\"\n    [ -z \"$config_path\" ] || params=\"$params -path $config_path\"\n    [ -z \"$config_subPort\" ] || params=\"$params -subPort $config_subPort\"\n    [ -z \"$config_subPath\" ] || params=\"$params -subPath $config_subPath\"\n    /usr/local/s-ui/sui setting ${params}\n    before_show_menu\n}\n\nview_setting() {\n    /usr/local/s-ui/sui setting -show\n    view_uri\n    before_show_menu\n}\n\nview_uri() {\n    info=$(/usr/local/s-ui/sui uri)\n    if [[ $? != 0 ]]; then\n        LOGE \"Get current uri error\"\n        before_show_menu\n    fi\n    LOGI \"You may access the Panel with following URL(s):\"\n    echo -e \"${green}${info}${plain}\"\n}\n\nstart() {\n    check_status $1\n    if [[ $? == 0 ]]; then\n        echo \"\"\n        LOGI -e \"${1} is running, No need to start again, If you need to restart, please select restart\"\n    else\n        systemctl start $1\n        sleep 2\n        check_status $1\n        if [[ $? == 0 ]]; then\n            LOGI \"${1} Started Successfully\"\n        else\n            LOGE \"Failed to start ${1}, Probably because it takes longer than two seconds to start, Please check the log information later\"\n        fi\n    fi\n\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\nstop() {\n    check_status $1\n    if [[ $? == 1 ]]; then\n        echo \"\"\n        LOGI \"${1} stopped, No need to stop again!\"\n    else\n        systemctl stop $1\n        sleep 2\n        check_status\n        if [[ $? == 1 ]]; then\n            LOGI \"${1} stopped successfully\"\n        else\n            LOGE \"Failed to stop ${1}, Probably because the stop time exceeds two seconds, Please check the log information later\"\n        fi\n    fi\n\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\nrestart() {\n    systemctl restart $1\n    sleep 2\n    check_status $1\n    if [[ $? == 0 ]]; then\n        LOGI \"${1} Restarted successfully\"\n    else\n        LOGE \"Failed to restart ${1}, Probably because it takes longer than two seconds to start, Please check the log information later\"\n    fi\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\nstatus() {\n    systemctl status s-ui -l\n    if [[ $# == 0 ]]; then\n        before_show_menu\n    fi\n}\n\nenable() {\n    systemctl enable $1\n    if [[ $? == 0 ]]; then\n        LOGI \"Set ${1} to boot automatically on startup successfully\"\n    else\n        LOGE \"Failed to set ${1} Autostart\"\n    fi\n\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\ndisable() {\n    systemctl disable $1\n    if [[ $? == 0 ]]; then\n        LOGI \"Autostart ${1} Cancelled successfully\"\n    else\n        LOGE \"Failed to cancel ${1} autostart\"\n    fi\n\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\nshow_log() {\n    journalctl -u $1.service -e --no-pager -f\n    if [[ $# == 1 ]]; then\n        before_show_menu\n    fi\n}\n\nupdate_shell() {\n    wget -O /usr/bin/s-ui -N --no-check-certificate https://github.com/alireza0/s-ui/raw/main/s-ui.sh\n    if [[ $? != 0 ]]; then\n        echo \"\"\n        LOGE \"Failed to download script, Please check whether the machine can connect Github\"\n        before_show_menu\n    else\n        chmod +x /usr/bin/s-ui\n        LOGI \"Upgrade script succeeded, Please rerun the script\" && exit 0\n    fi\n}\n\ncheck_status() {\n    if [[ ! -f \"/etc/systemd/system/$1.service\" ]]; then\n        return 2\n    fi\n    temp=$(systemctl status \"$1\" | grep Active | awk '{print $3}' | cut -d \"(\" -f2 | cut -d \")\" -f1)\n    if [[ x\"${temp}\" == x\"running\" ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\ncheck_enabled() {\n    temp=$(systemctl is-enabled $1)\n    if [[ x\"${temp}\" == x\"enabled\" ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\ncheck_uninstall() {\n    check_status s-ui\n    if [[ $? != 2 ]]; then\n        echo \"\"\n        LOGE \"Panel is already installed, Please do not reinstall\"\n        if [[ $# == 0 ]]; then\n            before_show_menu\n        fi\n        return 1\n    else\n        return 0\n    fi\n}\n\ncheck_install() {\n    check_status s-ui\n    if [[ $? == 2 ]]; then\n        echo \"\"\n        LOGE \"Please install the panel first\"\n        if [[ $# == 0 ]]; then\n            before_show_menu\n        fi\n        return 1\n    else\n        return 0\n    fi\n}\n\nshow_status() {\n    check_status $1\n    case $? in\n    0)\n        echo -e \"${1} state: ${green}Running${plain}\"\n        show_enable_status $1\n        ;;\n    1)\n        echo -e \"${1} state: ${yellow}Not Running${plain}\"\n        show_enable_status $1\n        ;;\n    2)\n        echo -e \"${1} state: ${red}Not Installed${plain}\"\n        ;;\n    esac\n}\n\nshow_enable_status() {\n    check_enabled $1\n    if [[ $? == 0 ]]; then\n        echo -e \"Start ${1} automatically: ${green}Yes${plain}\"\n    else\n        echo -e \"Start ${1} automatically: ${red}No${plain}\"\n    fi\n}\n\ncheck_s-ui_status() {\n    count=$(ps -ef | grep \"sui\" | grep -v \"grep\" | wc -l)\n    if [[ count -ne 0 ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nshow_s-ui_status() {\n    check_s-ui_status\n    if [[ $? == 0 ]]; then\n        echo -e \"s-ui state: ${green}Running${plain}\"\n    else\n        echo -e \"s-ui state: ${red}Not Running${plain}\"\n    fi\n}\n\nbbr_menu() {\n    echo -e \"${green}\\t1.${plain} Enable BBR\"\n    echo -e \"${green}\\t2.${plain} Disable BBR\"\n    echo -e \"${green}\\t0.${plain} Back to Main Menu\"\n    read -p \"Choose an option: \" choice\n    case \"$choice\" in\n    0)\n        show_menu\n        ;;\n    1)\n        enable_bbr\n        ;;\n    2)\n        disable_bbr\n        ;;\n    *) echo \"Invalid choice\" ;;\n    esac\n}\n\ndisable_bbr() {\n    if ! grep -q \"net.core.default_qdisc=fq\" /etc/sysctl.conf || ! grep -q \"net.ipv4.tcp_congestion_control=bbr\" /etc/sysctl.conf; then\n        echo -e \"${yellow}BBR is not currently enabled.${plain}\"\n        exit 0\n    fi\n    sed -i 's/net.core.default_qdisc=fq/net.core.default_qdisc=pfifo_fast/' /etc/sysctl.conf\n    sed -i 's/net.ipv4.tcp_congestion_control=bbr/net.ipv4.tcp_congestion_control=cubic/' /etc/sysctl.conf\n    sysctl -p\n    if [[ $(sysctl net.ipv4.tcp_congestion_control | awk '{print $3}') == \"cubic\" ]]; then\n        echo -e \"${green}BBR has been replaced with CUBIC successfully.${plain}\"\n    else\n        echo -e \"${red}Failed to replace BBR with CUBIC. Please check your system configuration.${plain}\"\n    fi\n}\n\nenable_bbr() {\n    if grep -q \"net.core.default_qdisc=fq\" /etc/sysctl.conf && grep -q \"net.ipv4.tcp_congestion_control=bbr\" /etc/sysctl.conf; then\n        echo -e \"${green}BBR is already enabled!${plain}\"\n        exit 0\n    fi\n    case \"${release}\" in\n    ubuntu | debian | armbian)\n        apt-get update && apt-get install -yqq --no-install-recommends ca-certificates\n        ;;\n    centos | almalinux | rocky | oracle)\n        yum -y update && yum -y install ca-certificates\n        ;;\n    fedora)\n        dnf -y update && dnf -y install ca-certificates\n        ;;\n    arch | manjaro | parch)\n        pacman -Sy --noconfirm ca-certificates\n        ;;\n    *)\n        echo -e \"${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\\n\"\n        exit 1\n        ;;\n    esac\n    echo \"net.core.default_qdisc=fq\" | tee -a /etc/sysctl.conf\n    echo \"net.ipv4.tcp_congestion_control=bbr\" | tee -a /etc/sysctl.conf\n    sysctl -p\n    if [[ $(sysctl net.ipv4.tcp_congestion_control | awk '{print $3}') == \"bbr\" ]]; then\n        echo -e \"${green}BBR has been enabled successfully.${plain}\"\n    else\n        echo -e \"${red}Failed to enable BBR. Please check your system configuration.${plain}\"\n    fi\n}\n\ninstall_acme() {\n    cd ~\n    LOGI \"install acme...\"\n    curl https://get.acme.sh | sh\n    if [ $? -ne 0 ]; then\n        LOGE \"install acme failed\"\n        return 1\n    else\n        LOGI \"install acme succeed\"\n    fi\n    return 0\n}\n\nssl_cert_issue_main() {\n    echo -e \"${green}\\t1.${plain} Get SSL\"\n    echo -e \"${green}\\t2.${plain} Revoke\"\n    echo -e \"${green}\\t3.${plain} Force Renew\"\n    echo -e \"${green}\\t4.${plain} Self-signed Certificate\"\n    read -p \"Choose an option: \" choice\n    case \"$choice\" in\n        1) ssl_cert_issue ;;\n        2) \n            local domain=\"\"\n            read -p \"Please enter your domain name to revoke the certificate: \" domain\n            ~/.acme.sh/acme.sh --revoke -d ${domain}\n            LOGI \"Certificate revoked\"\n            ;;\n        3)\n            local domain=\"\"\n            read -p \"Please enter your domain name to forcefully renew an SSL certificate: \" domain\n            ~/.acme.sh/acme.sh --renew -d ${domain} --force ;;\n        4)\n            generate_self_signed_cert\n            ;;\n        *) echo \"Invalid choice\" ;;\n    esac\n}\n\nssl_cert_issue() {\n    if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then\n        echo \"acme.sh could not be found. we will install it\"\n        install_acme\n        if [ $? -ne 0 ]; then\n            LOGE \"install acme failed, please check logs\"\n            exit 1\n        fi\n    fi\n    case \"${release}\" in\n    ubuntu | debian | armbian)\n        apt update && apt install socat -y\n        ;;\n    centos | almalinux | rocky | oracle)\n        yum -y update && yum -y install socat\n        ;;\n    fedora)\n        dnf -y update && dnf -y install socat\n        ;;\n    arch | manjaro | parch)\n        pacman -Sy --noconfirm socat\n        ;;\n    *)\n        echo -e \"${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\\n\"\n        exit 1\n        ;;\n    esac\n    if [ $? -ne 0 ]; then\n        LOGE \"install socat failed, please check logs\"\n        exit 1\n    else\n        LOGI \"install socat succeed...\"\n    fi\n\n    local domain=\"\"\n    read -p \"Please enter your domain name:\" domain\n    LOGD \"your domain is:${domain},check it...\"\n    local currentCert=$(~/.acme.sh/acme.sh --list | tail -1 | awk '{print $1}')\n\n    if [ ${currentCert} == ${domain} ]; then\n        local certInfo=$(~/.acme.sh/acme.sh --list)\n        LOGE \"system already has certs here,can not issue again,current certs details:\"\n        LOGI \"$certInfo\"\n        exit 1\n    else\n        LOGI \"your domain is ready for issuing cert now...\"\n    fi\n\n    certPath=\"/root/cert/${domain}\"\n    if [ ! -d \"$certPath\" ]; then\n        mkdir -p \"$certPath\"\n    else\n        rm -rf \"$certPath\"\n        mkdir -p \"$certPath\"\n    fi\n\n    local WebPort=80\n    read -p \"please choose which port do you use,default will be 80 port:\" WebPort\n    if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then\n        LOGE \"your input ${WebPort} is invalid,will use default port\"\n    fi\n    LOGI \"will use port:${WebPort} to issue certs,please make sure this port is open...\"\n    ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt\n    ~/.acme.sh/acme.sh --issue -d ${domain} --standalone --httpport ${WebPort}\n    if [ $? -ne 0 ]; then\n        LOGE \"issue certs failed,please check logs\"\n        rm -rf ~/.acme.sh/${domain}\n        exit 1\n    else\n        LOGE \"issue certs succeed,installing certs...\"\n    fi\n    ~/.acme.sh/acme.sh --installcert -d ${domain} \\\n        --key-file /root/cert/${domain}/privkey.pem \\\n        --fullchain-file /root/cert/${domain}/fullchain.pem\n\n    if [ $? -ne 0 ]; then\n        LOGE \"install certs failed,exit\"\n        rm -rf ~/.acme.sh/${domain}\n        exit 1\n    else\n        LOGI \"install certs succeed,enable auto renew...\"\n    fi\n\n    ~/.acme.sh/acme.sh --upgrade --auto-upgrade\n    if [ $? -ne 0 ]; then\n        LOGE \"auto renew failed, certs details:\"\n        ls -lah cert/*\n        chmod 755 $certPath/*\n        exit 1\n    else\n        LOGI \"auto renew succeed, certs details:\"\n        ls -lah cert/*\n        chmod 755 $certPath/*\n    fi\n}\n\nssl_cert_issue_CF() {\n    echo -E \"\"\n    LOGD \"******Instructions for use******\"\n    echo \"1) New certificate from Cloudflare\"\n    echo \"2) Force renew existing Certificates\"\n    echo \"3) Back to Menu\"\n    read -p \"Enter your choice [1-3]: \" choice\n\n    certPath=\"/root/cert-CF\"\n\n    case $choice in\n        1|2)\n            force_flag=\"\"\n            if [ \"$choice\" -eq 2 ]; then\n                force_flag=\"--force\"\n                echo \"Forcing SSL certificate reissuance...\"\n            else\n                echo \"Starting SSL certificate issuance...\"\n            fi\n            \n            LOGD \"******Instructions for use******\"\n            LOGI \"This Acme script requires the following data:\"\n            LOGI \"1.Cloudflare Registered e-mail\"\n            LOGI \"2.Cloudflare Global API Key\"\n            LOGI \"3.The domain name that has been resolved DNS to the current server by Cloudflare\"\n            LOGI \"4.The script applies for a certificate. The default installation path is /root/cert \"\n            confirm \"Confirmed?[y/n]\" \"y\"\n            if [ $? -eq 0 ]; then\n                if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then\n                    echo \"acme.sh could not be found. Installing...\"\n                    install_acme\n                    if [ $? -ne 0 ]; then\n                        LOGE \"Install acme failed, please check logs\"\n                        exit 1\n                    fi\n                fi\n\n                CF_Domain=\"\"\n                if [ ! -d \"$certPath\" ]; then\n                    mkdir -p $certPath\n                else\n                    rm -rf $certPath\n                    mkdir -p $certPath\n                fi\n\n                LOGD \"Please set a domain name:\"\n                read -p \"Input your domain here: \" CF_Domain\n                LOGD \"Your domain name is set to: ${CF_Domain}\"\n\n                CF_GlobalKey=\"\"\n                CF_AccountEmail=\"\"\n                LOGD \"Please set the API key:\"\n                read -p \"Input your key here: \" CF_GlobalKey\n                LOGD \"Your API key is: ${CF_GlobalKey}\"\n\n                LOGD \"Please set up registered email:\"\n                read -p \"Input your email here: \" CF_AccountEmail\n                LOGD \"Your registered email address is: ${CF_AccountEmail}\"\n\n                ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt\n                if [ $? -ne 0 ]; then\n                    LOGE \"Default CA, Let's Encrypt failed, script exiting...\"\n                    exit 1\n                fi\n\n                export CF_Key=\"${CF_GlobalKey}\"\n                export CF_Email=\"${CF_AccountEmail}\"\n\n                ~/.acme.sh/acme.sh --issue --dns dns_cf -d ${CF_Domain} -d *.${CF_Domain} $force_flag --log\n                if [ $? -ne 0 ]; then\n                    LOGE \"Certificate issuance failed, script exiting...\"\n                    exit 1\n                else\n                    LOGI \"Certificate issued Successfully, Installing...\"\n                fi\n\n                mkdir -p ${certPath}/${CF_Domain}\n                if [ $? -ne 0 ]; then\n                    LOGE \"Failed to create directory: ${certPath}/${CF_Domain}\"\n                    exit 1\n                fi\n\n                ~/.acme.sh/acme.sh --installcert -d ${CF_Domain} -d *.${CF_Domain} \\\n                    --fullchain-file ${certPath}/${CF_Domain}/fullchain.pem \\\n                    --key-file ${certPath}/${CF_Domain}/privkey.pem\n\n                if [ $? -ne 0 ]; then\n                    LOGE \"Certificate installation failed, script exiting...\"\n                    exit 1\n                else\n                    LOGI \"Certificate installed Successfully, Turning on automatic updates...\"\n                fi\n\n                ~/.acme.sh/acme.sh --upgrade --auto-upgrade\n                if [ $? -ne 0 ]; then\n                    LOGE \"Auto update setup failed, script exiting...\"\n                    exit 1\n                else\n                    LOGI \"The certificate is installed and auto-renewal is turned on.\"\n                    ls -lah ${certPath}/${CF_Domain}\n                    chmod 755 ${certPath}/${CF_Domain}\n                fi\n            fi\n            show_menu\n            ;;\n        3)\n            echo \"Exiting...\"\n            show_menu\n            ;;\n        *)\n            echo \"Invalid choice, please select again.\"\n            show_menu\n            ;;\n    esac\n}\n\ngenerate_self_signed_cert() {\n    cert_dir=\"/etc/sing-box\"\n    mkdir -p \"$cert_dir\"\n    LOGI \"Choose certificate type:\"\n    echo -e \"${green}\\t1.${plain} Ed25519 (*recommended*)\"\n    echo -e \"${green}\\t2.${plain} RSA 2048\"\n    echo -e \"${green}\\t3.${plain} RSA 4096\"\n    echo -e \"${green}\\t4.${plain} ECDSA prime256v1\"\n    echo -e \"${green}\\t5.${plain} ECDSA secp384r1\"\n    read -p \"Enter your choice [1-5, default 1]: \" cert_type\n    cert_type=${cert_type:-1}\n\n    case \"$cert_type\" in\n        1)\n            algo=\"ed25519\"\n            key_opt=\"-newkey ed25519\"\n            ;;\n        2)\n            algo=\"rsa\"\n            key_opt=\"-newkey rsa:2048\"\n            ;;\n        3)\n            algo=\"rsa\"\n            key_opt=\"-newkey rsa:4096\"\n            ;;\n        4)\n            algo=\"ecdsa\"\n            key_opt=\"-newkey ec -pkeyopt ec_paramgen_curve:prime256v1\"\n            ;;\n        5)\n            algo=\"ecdsa\"\n            key_opt=\"-newkey ec -pkeyopt ec_paramgen_curve:secp384r1\"\n            ;;\n        *)\n            algo=\"ed25519\"\n            key_opt=\"-newkey ed25519\"\n            ;;\n    esac\n\n    LOGI \"Generating self-signed certificate ($algo)...\"\n    sudo openssl req -x509 -nodes -days 3650 $key_opt \\\n        -keyout \"${cert_dir}/self.key\" \\\n        -out \"${cert_dir}/self.crt\" \\\n        -subj \"/CN=myserver\"\n    if [[ $? -eq 0 ]]; then\n        sudo chmod 600 \"${cert_dir}/self.\"*\n        LOGI \"Self-signed certificate generated successfully!\"\n        LOGI \"Certificate path: ${cert_dir}/self.crt\"\n        LOGI \"Key path: ${cert_dir}/self.key\"\n    else\n        LOGE \"Failed to generate self-signed certificate.\"\n    fi\n    before_show_menu\n}\n\nshow_usage() {\n    echo -e \"S-UI Control Menu Usage\"\n    echo -e \"------------------------------------------\"\n    echo -e \"SUBCOMMANDS:\" \n    echo -e \"s-ui              - Admin Management Script\"\n    echo -e \"s-ui start        - Start s-ui\"\n    echo -e \"s-ui stop         - Stop s-ui\"\n    echo -e \"s-ui restart      - Restart s-ui\"\n    echo -e \"s-ui status       - Current Status of s-ui\"\n    echo -e \"s-ui enable       - Enable Autostart on OS Startup\"\n    echo -e \"s-ui disable      - Disable Autostart on OS Startup\"\n    echo -e \"s-ui log          - Check s-ui Logs\"\n    echo -e \"s-ui update       - Update\"\n    echo -e \"s-ui install      - Install\"\n    echo -e \"s-ui uninstall    - Uninstall\"\n    echo -e \"s-ui help         - Control Menu Usage\"\n    echo -e \"------------------------------------------\"\n}\n\nshow_menu() {\n  echo -e \"\n  ${green}S-UI Admin Management Script ${plain}\n————————————————————————————————\n  ${green}0.${plain} Exit\n————————————————————————————————\n  ${green}1.${plain} Install\n  ${green}2.${plain} Update\n  ${green}3.${plain} Custom Version\n  ${green}4.${plain} Uninstall\n————————————————————————————————\n  ${green}5.${plain} Reset admin credentials to default\n  ${green}6.${plain} Set admin credentials\n  ${green}7.${plain} View admin credentials\n————————————————————————————————\n  ${green}8.${plain} Reset Panel Settings\n  ${green}9.${plain} Set Panel settings\n  ${green}10.${plain} View Panel Settings\n————————————————————————————————\n  ${green}11.${plain} S-UI Start\n  ${green}12.${plain} S-UI Stop\n  ${green}13.${plain} S-UI Restart\n  ${green}14.${plain} S-UI Check State\n  ${green}15.${plain} S-UI Check Logs\n  ${green}16.${plain} S-UI Enable Autostart\n  ${green}17.${plain} S-UI Disable Autostart\n————————————————————————————————\n  ${green}18.${plain} Enable or Disable BBR\n  ${green}19.${plain} SSL Certificate Management\n  ${green}20.${plain} Cloudflare SSL Certificate\n————————————————————————————————\n \"\n    show_status s-ui\n    echo && read -p \"Please enter your selection [0-20]: \" num\n\n    case \"${num}\" in\n    0)\n        exit 0\n        ;;\n    1)\n        check_uninstall && install\n        ;;\n    2)\n        check_install && update\n        ;;\n    3)\n        check_install && custom_version\n        ;;\n    4)\n        check_install && uninstall\n        ;;\n    5)\n        check_install && reset_admin\n        ;;\n    6)\n        check_install && set_admin\n        ;;\n    7)\n        check_install && view_admin\n        ;;\n    8)\n        check_install && reset_setting\n        ;;\n    9)\n        check_install && set_setting\n        ;;\n    10)\n        check_install && view_setting\n        ;;\n    11)\n        check_install && start s-ui\n        ;;\n    12)\n        check_install && stop s-ui\n        ;;\n    13)\n        check_install && restart s-ui\n        ;;\n    14)\n        check_install && status s-ui\n        ;;\n    15)\n        check_install && show_log s-ui\n        ;;\n    16)\n        check_install && enable s-ui\n        ;;\n    17)\n        check_install && disable s-ui\n        ;;\n    18)\n        bbr_menu\n        ;;\n    19)\n        ssl_cert_issue_main\n        ;;\n    20)\n        ssl_cert_issue_CF\n        ;;\n    *)\n        LOGE \"Please enter the correct number [0-20]\"\n        ;;\n    esac\n}\n\nif [[ $# > 0 ]]; then\n    case $1 in\n    \"start\")\n        check_install 0 && start s-ui 0\n        ;;\n    \"stop\")\n        check_install 0 && stop s-ui 0\n        ;;\n    \"restart\")\n        check_install 0 && restart s-ui 0\n        ;;\n    \"status\")\n        check_install 0 && status 0\n        ;;\n    \"enable\")\n        check_install 0 && enable s-ui 0\n        ;;\n    \"disable\")\n        check_install 0 && disable s-ui 0\n        ;;\n    \"log\")\n        check_install 0 && show_log s-ui 0\n        ;;\n    \"update\")\n        check_install 0 && update 0\n        ;;\n    \"install\")\n        check_uninstall 0 && install 0\n        ;;\n    \"uninstall\")\n        check_install 0 && uninstall 0\n        ;;\n    *) show_usage ;;\n    esac\nelse\n    show_menu\nfi\n"
  },
  {
    "path": "service/client.go",
    "content": "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.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype ClientService struct{}\n\nfunc (s *ClientService) Get(id string) (*[]model.Client, error) {\n\tif id == \"\" {\n\t\treturn s.GetAll()\n\t}\n\treturn s.getById(id)\n}\n\nfunc (s *ClientService) getById(id string) (*[]model.Client, error) {\n\tdb := database.GetDB()\n\tvar client []model.Client\n\terr := db.Model(model.Client{}).Where(\"id in ?\", strings.Split(id, \",\")).Scan(&client).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &client, nil\n}\n\nfunc (s *ClientService) GetAll() (*[]model.Client, error) {\n\tdb := database.GetDB()\n\tvar clients []model.Client\n\terr := db.Model(model.Client{}).\n\t\tSelect(\"`id`, `enable`, `name`, `desc`, `group`, `inbounds`, `up`, `down`, `volume`, `expiry`\").\n\t\tScan(&clients).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &clients, nil\n}\n\nfunc (s *ClientService) Save(tx *gorm.DB, act string, data json.RawMessage, hostname string) ([]uint, error) {\n\tvar err error\n\tvar inboundIds []uint\n\n\tswitch act {\n\tcase \"new\", \"edit\":\n\t\tvar client model.Client\n\t\terr = json.Unmarshal(data, &client)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = s.updateLinksWithFixedInbounds(tx, []*model.Client{&client}, hostname)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif act == \"edit\" {\n\t\t\t// Find changed inbounds\n\t\t\tinboundIds, err = s.findInboundsChanges(tx, &client, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\terr = json.Unmarshal(client.Inbounds, &inboundIds)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\terr = tx.Save(&client).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"addbulk\":\n\t\tvar clients []*model.Client\n\t\terr = json.Unmarshal(data, &clients)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = json.Unmarshal(clients[0].Inbounds, &inboundIds)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = s.updateLinksWithFixedInbounds(tx, clients, hostname)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = tx.Save(clients).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"editbulk\":\n\t\tvar clients []*model.Client\n\t\terr = json.Unmarshal(data, &clients)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, client := range clients {\n\t\t\tchangedInboundIds, err := s.findInboundsChanges(tx, client, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif len(changedInboundIds) > 0 {\n\t\t\t\tinboundIds = common.UnionUintArray(inboundIds, changedInboundIds)\n\t\t\t}\n\t\t}\n\t\tif len(inboundIds) > 0 {\n\t\t\terr = s.updateLinksWithFixedInbounds(tx, clients, hostname)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\terr = tx.Save(clients).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"delbulk\":\n\t\tvar ids []uint\n\t\terr = json.Unmarshal(data, &ids)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, id := range ids {\n\t\t\tvar client model.Client\n\t\t\terr = tx.Where(\"id = ?\", id).First(&client).Error\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvar clientInbounds []uint\n\t\t\terr = json.Unmarshal(client.Inbounds, &clientInbounds)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinboundIds = common.UnionUintArray(inboundIds, clientInbounds)\n\t\t}\n\t\terr = tx.Where(\"id in ?\", ids).Delete(model.Client{}).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"del\":\n\t\tvar id uint\n\t\terr = json.Unmarshal(data, &id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar client model.Client\n\t\terr = tx.Where(\"id = ?\", id).First(&client).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = json.Unmarshal(client.Inbounds, &inboundIds)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = tx.Where(\"id = ?\", id).Delete(model.Client{}).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, common.NewErrorf(\"unknown action: %s\", act)\n\t}\n\n\treturn inboundIds, nil\n}\n\nfunc (s *ClientService) updateLinksWithFixedInbounds(tx *gorm.DB, clients []*model.Client, hostname string) error {\n\tvar err error\n\tvar inbounds []model.Inbound\n\tvar inboundIds []uint\n\n\terr = json.Unmarshal(clients[0].Inbounds, &inboundIds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Zero inbounds means removing local links only\n\tif len(inboundIds) > 0 {\n\t\terr = tx.Model(model.Inbound{}).Preload(\"Tls\").Where(\"id in ? and type in ?\", inboundIds, util.InboundTypeWithLink).Find(&inbounds).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor index, client := range clients {\n\t\tvar clientLinks []map[string]string\n\t\terr = json.Unmarshal(client.Links, &clientLinks)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewClientLinks := []map[string]string{}\n\t\tfor _, inbound := range inbounds {\n\t\t\tnewLinks := util.LinkGenerator(client.Config, &inbound, hostname)\n\t\t\tfor _, newLink := range newLinks {\n\t\t\t\tnewClientLinks = append(newClientLinks, map[string]string{\n\t\t\t\t\t\"remark\": inbound.Tag,\n\t\t\t\t\t\"type\":   \"local\",\n\t\t\t\t\t\"uri\":    newLink,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Add non local links\n\t\tfor _, clientLink := range clientLinks {\n\t\t\tif clientLink[\"type\"] != \"local\" {\n\t\t\t\tnewClientLinks = append(newClientLinks, clientLink)\n\t\t\t}\n\t\t}\n\n\t\tclients[index].Links, err = json.MarshalIndent(newClientLinks, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *ClientService) UpdateClientsOnInboundAdd(tx *gorm.DB, initIds string, inboundId uint, hostname string) error {\n\tclientIds := strings.Split(initIds, \",\")\n\tvar clients []model.Client\n\terr := tx.Model(model.Client{}).Where(\"id in ?\", clientIds).Find(&clients).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar inbound model.Inbound\n\terr = tx.Model(model.Inbound{}).Preload(\"Tls\").Where(\"id = ?\", inboundId).Find(&inbound).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, client := range clients {\n\t\t// Add inbounds\n\t\tvar clientInbounds []uint\n\t\tjson.Unmarshal(client.Inbounds, &clientInbounds)\n\t\tclientInbounds = append(clientInbounds, inboundId)\n\t\tclient.Inbounds, err = json.MarshalIndent(clientInbounds, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Add links\n\t\tvar clientLinks, newClientLinks []map[string]string\n\t\tjson.Unmarshal(client.Links, &clientLinks)\n\t\tnewLinks := util.LinkGenerator(client.Config, &inbound, hostname)\n\t\tfor _, newLink := range newLinks {\n\t\t\tnewClientLinks = append(newClientLinks, map[string]string{\n\t\t\t\t\"remark\": inbound.Tag,\n\t\t\t\t\"type\":   \"local\",\n\t\t\t\t\"uri\":    newLink,\n\t\t\t})\n\t\t}\n\t\tfor _, clientLink := range clientLinks {\n\t\t\tif clientLink[\"remark\"] != inbound.Tag {\n\t\t\t\tnewClientLinks = append(newClientLinks, clientLink)\n\t\t\t}\n\t\t}\n\n\t\tclient.Links, err = json.MarshalIndent(newClientLinks, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = tx.Save(&client).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *ClientService) UpdateClientsOnInboundDelete(tx *gorm.DB, id uint, tag string) error {\n\tvar clientIds []uint\n\terr := tx.Raw(\"SELECT clients.id FROM clients, json_each(clients.inbounds) AS je WHERE je.value = ?\", id).Scan(&clientIds).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(clientIds) == 0 {\n\t\treturn nil\n\t}\n\tvar clients []model.Client\n\terr = tx.Model(model.Client{}).Where(\"id IN ?\", clientIds).Find(&clients).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, client := range clients {\n\t\t// Delete inbounds\n\t\tvar clientInbounds, newClientInbounds []uint\n\t\tjson.Unmarshal(client.Inbounds, &clientInbounds)\n\t\tfor _, clientInbound := range clientInbounds {\n\t\t\tif clientInbound != id {\n\t\t\t\tnewClientInbounds = append(newClientInbounds, clientInbound)\n\t\t\t}\n\t\t}\n\t\tclient.Inbounds, err = json.MarshalIndent(newClientInbounds, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Delete links\n\t\tvar clientLinks, newClientLinks []map[string]string\n\t\tjson.Unmarshal(client.Links, &clientLinks)\n\t\tfor _, clientLink := range clientLinks {\n\t\t\tif clientLink[\"remark\"] != tag {\n\t\t\t\tnewClientLinks = append(newClientLinks, clientLink)\n\t\t\t}\n\t\t}\n\t\tclient.Links, err = json.MarshalIndent(newClientLinks, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = tx.Save(&client).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *ClientService) UpdateLinksByInboundChange(tx *gorm.DB, inbounds *[]model.Inbound, hostname string, oldTag string) error {\n\tvar err error\n\tfor _, inbound := range *inbounds {\n\t\tvar clientIds []uint\n\t\terr = tx.Raw(\"SELECT clients.id FROM clients, json_each(clients.inbounds) AS je WHERE je.value = ?\", inbound.Id).Scan(&clientIds).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(clientIds) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tvar clients []model.Client\n\t\terr = tx.Model(model.Client{}).Where(\"id IN ?\", clientIds).Find(&clients).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, client := range clients {\n\t\t\tvar clientLinks, newClientLinks []map[string]string\n\t\t\tjson.Unmarshal(client.Links, &clientLinks)\n\t\t\tnewLinks := util.LinkGenerator(client.Config, &inbound, hostname)\n\t\t\tfor _, newLink := range newLinks {\n\t\t\t\tnewClientLinks = append(newClientLinks, map[string]string{\n\t\t\t\t\t\"remark\": inbound.Tag,\n\t\t\t\t\t\"type\":   \"local\",\n\t\t\t\t\t\"uri\":    newLink,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor _, clientLink := range clientLinks {\n\t\t\t\tif clientLink[\"type\"] != \"local\" || (clientLink[\"remark\"] != inbound.Tag && clientLink[\"remark\"] != oldTag) {\n\t\t\t\t\tnewClientLinks = append(newClientLinks, clientLink)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclient.Links, err = json.MarshalIndent(newClientLinks, \"\", \"  \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = tx.Save(&client).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *ClientService) DepleteClients() ([]uint, error) {\n\tvar err error\n\tvar clients []model.Client\n\tvar changes []model.Changes\n\tvar users []string\n\tvar inboundIds []uint\n\n\tdt := time.Now().Unix()\n\tdb := database.GetDB()\n\n\ttx := db.Begin()\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t\t_, err1 := db.Raw(\"PRAGMA wal_checkpoint(FULL)\").Rows()\n\t\t\tif err1 != nil {\n\t\t\t\tlogger.Error(\"Error checkpointing WAL: \", err1.Error())\n\t\t\t}\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\t// Reset clients\n\tinboundIds, err = s.ResetClients(tx, dt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Deplete clients\n\terr = tx.Model(model.Client{}).Where(\"enable = true AND ((volume >0 AND up+down > volume) OR (expiry > 0 AND expiry < ?))\", dt).Scan(&clients).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, client := range clients {\n\t\tlogger.Debug(\"Client \", client.Name, \" is going to be disabled\")\n\t\tusers = append(users, client.Name)\n\t\tvar userInbounds []uint\n\t\tjson.Unmarshal(client.Inbounds, &userInbounds)\n\t\t// Find changed inbounds\n\t\tinboundIds = common.UnionUintArray(inboundIds, userInbounds)\n\t\tchanges = append(changes, model.Changes{\n\t\t\tDateTime: dt,\n\t\t\tActor:    \"DepleteJob\",\n\t\t\tKey:      \"clients\",\n\t\t\tAction:   \"disable\",\n\t\t\tObj:      json.RawMessage(\"\\\"\" + client.Name + \"\\\"\"),\n\t\t})\n\t}\n\n\t// Save changes\n\tif len(changes) > 0 {\n\t\terr = tx.Model(model.Client{}).Where(\"enable = true AND ((volume >0 AND up+down > volume) OR (expiry > 0 AND expiry < ?))\", dt).Update(\"enable\", false).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = tx.Model(model.Changes{}).Create(&changes).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tLastUpdate = dt\n\t}\n\n\treturn inboundIds, nil\n}\n\nfunc (s *ClientService) ResetClients(tx *gorm.DB, dt int64) ([]uint, error) {\n\tvar err error\n\tvar resetClients, allClients []*model.Client\n\tvar changes []model.Changes\n\tvar inboundIds []uint\n\t// Set delay start without periodic reset\n\terr = tx.Model(model.Client{}).\n\t\tWhere(\"enable = true AND delay_start = true AND auto_reset = false AND (Up + Down) > 0\").Find(&resetClients).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, client := range resetClients {\n\t\tclient.Expiry = dt + (int64(client.ResetDays) * 86400)\n\t\tclient.DelayStart = false\n\t\tchanges = append(changes, model.Changes{\n\t\t\tDateTime: dt,\n\t\t\tActor:    \"ResetJob\",\n\t\t\tKey:      \"clients\",\n\t\t\tAction:   \"reset\",\n\t\t\tObj:      json.RawMessage(\"\\\"\" + client.Name + \"\\\"\"),\n\t\t})\n\t}\n\tallClients = append(allClients, resetClients...)\n\n\t// Set delay start with periodic reset\n\terr = tx.Model(model.Client{}).\n\t\tWhere(\"enable = true AND delay_start = true AND auto_reset = true AND (Up + Down) > 0\").Find(&resetClients).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, client := range resetClients {\n\t\tclient.NextReset = dt + (int64(client.ResetDays) * 86400)\n\t\tclient.DelayStart = false\n\t\tchanges = append(changes, model.Changes{\n\t\t\tDateTime: dt,\n\t\t\tActor:    \"ResetJob\",\n\t\t\tKey:      \"clients\",\n\t\t\tAction:   \"reset\",\n\t\t\tObj:      json.RawMessage(\"\\\"\" + client.Name + \"\\\"\"),\n\t\t})\n\t}\n\tallClients = append(allClients, resetClients...)\n\n\t// Set periodic reset\n\terr = tx.Model(model.Client{}).\n\t\tWhere(\"delay_start = false AND auto_reset = true AND next_reset < ?\", dt).Find(&resetClients).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, client := range resetClients {\n\t\tclient.NextReset = dt + (int64(client.ResetDays) * 86400)\n\t\tclient.TotalUp += client.Up\n\t\tclient.TotalDown += client.Down\n\t\tclient.Up = 0\n\t\tclient.Down = 0\n\t\tif !client.Enable {\n\t\t\tclient.Enable = true\n\t\t\tvar clientInboundIds []uint\n\t\t\tjson.Unmarshal(client.Inbounds, &clientInboundIds)\n\t\t\tinboundIds = common.UnionUintArray(inboundIds, clientInboundIds)\n\t\t}\n\t}\n\tallClients = append(allClients, resetClients...)\n\n\t// Save clients\n\tif len(allClients) > 0 {\n\t\terr = tx.Save(allClients).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Save changes\n\tif len(changes) > 0 {\n\t\terr = tx.Model(model.Changes{}).Create(&changes).Error\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tLastUpdate = dt\n\t}\n\treturn inboundIds, nil\n}\n\nfunc (s *ClientService) findInboundsChanges(tx *gorm.DB, client *model.Client, fillOmitted bool) ([]uint, error) {\n\tvar err error\n\tvar oldClient model.Client\n\tvar oldInboundIds, newInboundIds []uint\n\terr = tx.Model(model.Client{}).Where(\"id = ?\", client.Id).First(&oldClient).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fillOmitted {\n\t\tclient.Links = oldClient.Links\n\t\tclient.Config = oldClient.Config\n\t}\n\terr = json.Unmarshal(oldClient.Inbounds, &oldInboundIds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(client.Inbounds, &newInboundIds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check client.Config changes\n\tif !bytes.Equal(oldClient.Config, client.Config) ||\n\t\toldClient.Name != client.Name ||\n\t\toldClient.Enable != client.Enable {\n\t\treturn common.UnionUintArray(oldInboundIds, newInboundIds), nil\n\t}\n\n\t// Check client.Inbounds changes\n\tdiffInbounds := common.DiffUintArray(oldInboundIds, newInboundIds)\n\n\treturn diffInbounds, nil\n}\n"
  },
  {
    "path": "service/config.go",
    "content": "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/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n)\n\nvar (\n\tLastUpdate          int64\n\tcorePtr             *core.Core\n\tstartCoreMu         sync.Mutex\n\tstartCoreInProgress bool\n\tlastStartFailTime   time.Time\n\tstartCooldown       = 15 * time.Second\n)\n\ntype ConfigService struct {\n\tClientService\n\tTlsService\n\tSettingService\n\tInboundService\n\tOutboundService\n\tServicesService\n\tEndpointService\n}\n\ntype SingBoxConfig struct {\n\tLog          json.RawMessage   `json:\"log\"`\n\tDns          json.RawMessage   `json:\"dns\"`\n\tNtp          json.RawMessage   `json:\"ntp\"`\n\tInbounds     []json.RawMessage `json:\"inbounds\"`\n\tOutbounds    []json.RawMessage `json:\"outbounds\"`\n\tServices     []json.RawMessage `json:\"services\"`\n\tEndpoints    []json.RawMessage `json:\"endpoints\"`\n\tRoute        json.RawMessage   `json:\"route\"`\n\tExperimental json.RawMessage   `json:\"experimental\"`\n}\n\nfunc NewConfigService(core *core.Core) *ConfigService {\n\tcorePtr = core\n\treturn &ConfigService{}\n}\n\nfunc (s *ConfigService) GetConfig(data string) (*[]byte, error) {\n\tvar err error\n\tif len(data) == 0 {\n\t\tdata, err = s.SettingService.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tsingboxConfig := SingBoxConfig{}\n\terr = json.Unmarshal([]byte(data), &singboxConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsingboxConfig.Inbounds, err = s.InboundService.GetAllConfig(database.GetDB())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsingboxConfig.Outbounds, err = s.OutboundService.GetAllConfig(database.GetDB())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsingboxConfig.Services, err = s.ServicesService.GetAllConfig(database.GetDB())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsingboxConfig.Endpoints, err = s.EndpointService.GetAllConfig(database.GetDB())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawConfig, err := json.MarshalIndent(singboxConfig, \"\", \"  \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rawConfig, nil\n}\n\nfunc (s *ConfigService) StartCore() error {\n\tif corePtr.IsRunning() {\n\t\treturn nil\n\t}\n\tstartCoreMu.Lock()\n\tif startCoreInProgress {\n\t\tstartCoreMu.Unlock()\n\t\treturn nil\n\t}\n\tif time.Since(lastStartFailTime) < startCooldown {\n\t\tlogger.Info(\"start core cooldown \", startCooldown/time.Second, \" seconds\")\n\t\tstartCoreMu.Unlock()\n\t\treturn nil\n\t}\n\tstartCoreInProgress = true\n\tstartCoreMu.Unlock()\n\tdefer func() {\n\t\tstartCoreMu.Lock()\n\t\tstartCoreInProgress = false\n\t\tstartCoreMu.Unlock()\n\t}()\n\n\tlogger.Info(\"starting core\")\n\trawConfig, err := s.GetConfig(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = corePtr.Start(*rawConfig)\n\tif err != nil {\n\t\tstartCoreMu.Lock()\n\t\tlastStartFailTime = time.Now()\n\t\tstartCoreMu.Unlock()\n\t\tlogger.Error(\"start sing-box err:\", err.Error())\n\t\treturn err\n\t}\n\tlogger.Info(\"sing-box started\")\n\treturn nil\n}\n\nfunc (s *ConfigService) RestartCore() error {\n\terr := s.StopCore()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.StartCore()\n}\n\nfunc (s *ConfigService) restartCoreWithConfig(config json.RawMessage) error {\n\tstartCoreMu.Lock()\n\tif startCoreInProgress {\n\t\tstartCoreMu.Unlock()\n\t\treturn nil\n\t}\n\tstartCoreInProgress = true\n\tstartCoreMu.Unlock()\n\tdefer func() {\n\t\tstartCoreMu.Lock()\n\t\tstartCoreInProgress = false\n\t\tstartCoreMu.Unlock()\n\t}()\n\n\tif corePtr.IsRunning() {\n\t\tif err := corePtr.Stop(); err != nil {\n\t\t\tlogger.Error(\"restart sing-box err (stop):\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\trawConfig, err := s.GetConfig(string(config))\n\tif err != nil {\n\t\tlogger.Error(\"restart sing-box err (get config):\", err.Error())\n\t\treturn err\n\t}\n\tif err := corePtr.Start(*rawConfig); err != nil {\n\t\tlogger.Error(\"restart sing-box err (start):\", err.Error())\n\t\treturn err\n\t}\n\tlogger.Info(\"sing-box restarted with new config\")\n\treturn nil\n}\n\nfunc (s *ConfigService) StopCore() error {\n\terr := corePtr.Stop()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Info(\"sing-box stopped\")\n\treturn nil\n}\n\nfunc (s *ConfigService) CheckOutbound(tag string, link string) core.CheckOutboundResult {\n\tif tag == \"\" {\n\t\treturn core.CheckOutboundResult{Error: \"missing query parameter: tag\"}\n\t}\n\tif corePtr == nil || !corePtr.IsRunning() {\n\t\treturn core.CheckOutboundResult{Error: \"core not running\"}\n\t}\n\treturn core.CheckOutbound(corePtr.GetCtx(), tag, link)\n}\n\nfunc (s *ConfigService) Save(obj string, act string, data json.RawMessage, initUsers string, loginUser string, hostname string) ([]string, error) {\n\tvar err error\n\tvar objs []string = []string{obj}\n\n\tdb := database.GetDB()\n\ttx := db.Begin()\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t\t// Try to start core if it is not running\n\t\t\tif !corePtr.IsRunning() {\n\t\t\t\ts.StartCore()\n\t\t\t}\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\tswitch obj {\n\tcase \"clients\":\n\t\tvar inboundIds []uint\n\t\tinboundIds, err = s.ClientService.Save(tx, act, data, hostname)\n\t\tif err == nil && len(inboundIds) > 0 {\n\t\t\tobjs = append(objs, \"inbounds\")\n\t\t\terr = s.InboundService.RestartInbounds(tx, inboundIds)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, common.NewErrorf(\"failed to update users for inbounds: %v\", err)\n\t\t\t}\n\t\t}\n\tcase \"tls\":\n\t\terr = s.TlsService.Save(tx, act, data, hostname)\n\t\tobjs = append(objs, \"clients\", \"inbounds\")\n\tcase \"inbounds\":\n\t\terr = s.InboundService.Save(tx, act, data, initUsers, hostname)\n\t\tobjs = append(objs, \"clients\")\n\tcase \"outbounds\":\n\t\terr = s.OutboundService.Save(tx, act, data)\n\tcase \"services\":\n\t\terr = s.ServicesService.Save(tx, act, data)\n\tcase \"endpoints\":\n\t\terr = s.EndpointService.Save(tx, act, data)\n\tcase \"config\":\n\t\terr = s.SettingService.SaveConfig(tx, data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfigData := make(json.RawMessage, len(data))\n\t\tcopy(configData, data)\n\t\tgo func() { _ = s.restartCoreWithConfig(configData) }()\n\tcase \"settings\":\n\t\terr = s.SettingService.Save(tx, data)\n\tdefault:\n\t\treturn nil, common.NewError(\"unknown object: \", obj)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdt := time.Now().Unix()\n\terr = tx.Create(&model.Changes{\n\t\tDateTime: dt,\n\t\tActor:    loginUser,\n\t\tKey:      obj,\n\t\tAction:   act,\n\t\tObj:      data,\n\t}).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tLastUpdate = time.Now().Unix()\n\n\treturn objs, nil\n}\n\nfunc (s *ConfigService) CheckChanges(lu string) (bool, error) {\n\tif lu == \"\" {\n\t\treturn true, nil\n\t}\n\tif LastUpdate == 0 {\n\t\tdb := database.GetDB()\n\t\tvar count int64\n\t\terr := db.Model(model.Changes{}).Where(\"date_time > \" + lu).Count(&count).Error\n\t\tif err == nil {\n\t\t\tLastUpdate = time.Now().Unix()\n\t\t}\n\t\treturn count > 0, err\n\t} else {\n\t\tintLu, err := strconv.ParseInt(lu, 10, 64)\n\t\treturn LastUpdate > intLu, err\n\t}\n}\n\nfunc (s *ConfigService) GetChanges(actor string, chngKey string, count string) []model.Changes {\n\tc, _ := strconv.Atoi(count)\n\twhereString := \"`id`>0\"\n\tif len(actor) > 0 {\n\t\twhereString += \" and `actor`='\" + actor + \"'\"\n\t}\n\tif len(chngKey) > 0 {\n\t\twhereString += \" and `key`='\" + chngKey + \"'\"\n\t}\n\tdb := database.GetDB()\n\tvar chngs []model.Changes\n\terr := db.Model(model.Changes{}).Where(whereString).Order(\"`id` desc\").Limit(c).Scan(&chngs).Error\n\tif err != nil {\n\t\tlogger.Warning(err)\n\t}\n\treturn chngs\n}\n"
  },
  {
    "path": "service/endpoints.go",
    "content": "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/database/model\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype EndpointService struct {\n\tWarpService\n}\n\nfunc (o *EndpointService) GetAll() (*[]map[string]interface{}, error) {\n\tdb := database.GetDB()\n\tendpoints := []*model.Endpoint{}\n\terr := db.Model(model.Endpoint{}).Scan(&endpoints).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []map[string]interface{}\n\tfor _, endpoint := range endpoints {\n\t\tepData := map[string]interface{}{\n\t\t\t\"id\":   endpoint.Id,\n\t\t\t\"type\": endpoint.Type,\n\t\t\t\"tag\":  endpoint.Tag,\n\t\t\t\"ext\":  endpoint.Ext,\n\t\t}\n\t\tif endpoint.Options != nil {\n\t\t\tvar restFields map[string]json.RawMessage\n\t\t\tif err := json.Unmarshal(endpoint.Options, &restFields); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range restFields {\n\t\t\t\tepData[k] = v\n\t\t\t}\n\t\t}\n\t\tdata = append(data, epData)\n\t}\n\treturn &data, nil\n}\n\nfunc (o *EndpointService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error) {\n\tvar endpointsJson []json.RawMessage\n\tvar endpoints []*model.Endpoint\n\terr := db.Model(model.Endpoint{}).Scan(&endpoints).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, endpoint := range endpoints {\n\t\tendpointJson, err := endpoint.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpointsJson = append(endpointsJson, endpointJson)\n\t}\n\treturn endpointsJson, nil\n}\n\nfunc (s *EndpointService) Save(tx *gorm.DB, act string, data json.RawMessage) error {\n\tvar err error\n\n\tswitch act {\n\tcase \"new\", \"edit\":\n\t\tvar endpoint model.Endpoint\n\t\terr = endpoint.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif endpoint.Type == \"warp\" {\n\t\t\tif act == \"new\" {\n\t\t\t\terr = s.WarpService.RegisterWarp(&endpoint)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar old_license string\n\t\t\t\terr = tx.Model(model.Endpoint{}).Select(\"json_extract(ext, '$.license_key')\").Where(\"id = ?\", endpoint.Id).Find(&old_license).Error\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = s.WarpService.SetWarpLicense(old_license, &endpoint)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif corePtr.IsRunning() {\n\t\t\tconfigData, err := endpoint.MarshalJSON()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif act == \"edit\" {\n\t\t\t\tvar oldTag string\n\t\t\t\terr = tx.Model(model.Endpoint{}).Select(\"tag\").Where(\"id = ?\", endpoint.Id).Find(&oldTag).Error\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = corePtr.RemoveEndpoint(oldTag)\n\t\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = corePtr.AddEndpoint(configData)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = tx.Save(&endpoint).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"del\":\n\t\tvar tag string\n\t\terr = json.Unmarshal(data, &tag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif corePtr.IsRunning() {\n\t\t\terr = corePtr.RemoveEndpoint(tag)\n\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\terr = tx.Where(\"tag = ?\", tag).Delete(model.Endpoint{}).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn common.NewErrorf(\"unknown action: %s\", act)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/inbounds.go",
    "content": "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/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/util\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype InboundService struct {\n\tClientService\n}\n\nfunc (s *InboundService) Get(ids string) (*[]map[string]interface{}, error) {\n\tif ids == \"\" {\n\t\treturn s.GetAll()\n\t}\n\treturn s.getById(ids)\n}\n\nfunc (s *InboundService) getById(ids string) (*[]map[string]interface{}, error) {\n\tvar inbound []model.Inbound\n\tvar result []map[string]interface{}\n\tdb := database.GetDB()\n\terr := db.Model(model.Inbound{}).Where(\"id in ?\", strings.Split(ids, \",\")).Scan(&inbound).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, inb := range inbound {\n\t\tinbData, err := inb.MarshalFull()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, *inbData)\n\t}\n\treturn &result, nil\n}\n\nfunc (s *InboundService) GetAll() (*[]map[string]interface{}, error) {\n\tdb := database.GetDB()\n\tinbounds := []model.Inbound{}\n\terr := db.Model(model.Inbound{}).Scan(&inbounds).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []map[string]interface{}\n\tfor _, inbound := range inbounds {\n\t\tvar shadowtls_version uint\n\t\tss_managed := false\n\t\tinbData := map[string]interface{}{\n\t\t\t\"id\":     inbound.Id,\n\t\t\t\"type\":   inbound.Type,\n\t\t\t\"tag\":    inbound.Tag,\n\t\t\t\"tls_id\": inbound.TlsId,\n\t\t}\n\t\tif inbound.Options != nil {\n\t\t\tvar restFields map[string]json.RawMessage\n\t\t\tif err := json.Unmarshal(inbound.Options, &restFields); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinbData[\"listen\"] = restFields[\"listen\"]\n\t\t\tinbData[\"listen_port\"] = restFields[\"listen_port\"]\n\t\t\tif inbound.Type == \"shadowtls\" {\n\t\t\t\tjson.Unmarshal(restFields[\"version\"], &shadowtls_version)\n\t\t\t}\n\t\t\tif inbound.Type == \"shadowsocks\" {\n\t\t\t\tjson.Unmarshal(restFields[\"managed\"], &ss_managed)\n\t\t\t}\n\t\t}\n\t\tif s.hasUser(inbound.Type) &&\n\t\t\t!(inbound.Type == \"shadowtls\" && shadowtls_version < 3) &&\n\t\t\t!(inbound.Type == \"shadowsocks\" && ss_managed) {\n\t\t\tusers := []string{}\n\t\t\terr = db.Raw(\"SELECT clients.name FROM clients, json_each(clients.inbounds) as je WHERE je.value = ?\", inbound.Id).Scan(&users).Error\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinbData[\"users\"] = users\n\t\t}\n\n\t\tdata = append(data, inbData)\n\t}\n\treturn &data, nil\n}\n\nfunc (s *InboundService) FromIds(ids []uint) ([]*model.Inbound, error) {\n\tdb := database.GetDB()\n\tinbounds := []*model.Inbound{}\n\terr := db.Model(model.Inbound{}).Where(\"id in ?\", ids).Scan(&inbounds).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn inbounds, nil\n}\n\nfunc (s *InboundService) Save(tx *gorm.DB, act string, data json.RawMessage, initUserIds string, hostname string) error {\n\tvar err error\n\n\tswitch act {\n\tcase \"new\", \"edit\":\n\t\tvar inbound model.Inbound\n\t\terr = inbound.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif inbound.TlsId > 0 {\n\t\t\terr = tx.Model(model.Tls{}).Where(\"id = ?\", inbound.TlsId).Find(&inbound.Tls).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tvar oldTag string\n\t\tif act == \"edit\" {\n\t\t\terr = tx.Model(model.Inbound{}).Select(\"tag\").Where(\"id = ?\", inbound.Id).Find(&oldTag).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif corePtr.IsRunning() {\n\t\t\tif act == \"edit\" {\n\t\t\t\terr = corePtr.RemoveInbound(oldTag)\n\t\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinboundConfig, err := inbound.MarshalJSON()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif act == \"edit\" {\n\t\t\t\tinboundConfig, err = s.addUsers(tx, inboundConfig, inbound.Id, inbound.Type)\n\t\t\t} else {\n\t\t\t\tinboundConfig, err = s.initUsers(tx, inboundConfig, initUserIds, inbound.Type)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = corePtr.AddInbound(inboundConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = util.FillOutJson(&inbound, hostname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = tx.Save(&inbound).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch act {\n\t\tcase \"new\":\n\t\t\terr = s.ClientService.UpdateClientsOnInboundAdd(tx, initUserIds, inbound.Id, hostname)\n\t\tcase \"edit\":\n\t\t\terr = s.ClientService.UpdateLinksByInboundChange(tx, &[]model.Inbound{inbound}, hostname, oldTag)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"del\":\n\t\tvar tag string\n\t\terr = json.Unmarshal(data, &tag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif corePtr.IsRunning() {\n\t\t\terr = corePtr.RemoveInbound(tag)\n\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tvar id uint\n\t\terr = tx.Model(model.Inbound{}).Select(\"id\").Where(\"tag = ?\", tag).Scan(&id).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.ClientService.UpdateClientsOnInboundDelete(tx, id, tag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = tx.Where(\"tag = ?\", tag).Delete(model.Inbound{}).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn common.NewErrorf(\"unknown action: %s\", act)\n\t}\n\treturn nil\n}\n\nfunc (s *InboundService) UpdateOutJsons(tx *gorm.DB, inboundIds []uint, hostname string) error {\n\tvar inbounds []model.Inbound\n\terr := tx.Model(model.Inbound{}).Preload(\"Tls\").Where(\"id in ?\", inboundIds).Find(&inbounds).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, inbound := range inbounds {\n\t\terr = util.FillOutJson(&inbound, hostname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = tx.Model(model.Inbound{}).Where(\"tag = ?\", inbound.Tag).Update(\"out_json\", inbound.OutJson).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *InboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error) {\n\tvar inboundsJson []json.RawMessage\n\tvar inbounds []*model.Inbound\n\terr := db.Model(model.Inbound{}).Preload(\"Tls\").Find(&inbounds).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, inbound := range inbounds {\n\t\tinboundJson, err := inbound.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinboundJson, err = s.addUsers(db, inboundJson, inbound.Id, inbound.Type)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinboundsJson = append(inboundsJson, inboundJson)\n\t}\n\treturn inboundsJson, nil\n}\n\nfunc (s *InboundService) hasUser(inboundType string) bool {\n\tswitch inboundType {\n\tcase \"mixed\", \"socks\", \"http\", \"shadowsocks\", \"vmess\", \"trojan\", \"naive\", \"hysteria\", \"shadowtls\", \"tuic\", \"hysteria2\", \"vless\", \"anytls\":\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *InboundService) fetchUsers(db *gorm.DB, inboundType string, condition string, inbound map[string]interface{}) ([]json.RawMessage, error) {\n\tif inboundType == \"shadowtls\" {\n\t\tversion, _ := inbound[\"version\"].(float64)\n\t\tif int(version) < 3 {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tif inboundType == \"shadowsocks\" {\n\t\tmethod, _ := inbound[\"method\"].(string)\n\t\tif method == \"2022-blake3-aes-128-gcm\" {\n\t\t\tinboundType = \"shadowsocks16\"\n\t\t}\n\t}\n\n\tvar users []string\n\n\terr := db.Raw(\n\t\tfmt.Sprintf(`SELECT json_extract(clients.config, \"$.%s\")\n\t\tFROM clients WHERE enable = true AND %s`,\n\t\t\tinboundType, condition)).Scan(&users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar usersJson []json.RawMessage\n\tfor _, user := range users {\n\t\tif inboundType == \"vless\" && inbound[\"tls\"] == nil {\n\t\t\tuser = strings.Replace(user, \"xtls-rprx-vision\", \"\", -1)\n\t\t}\n\t\tusersJson = append(usersJson, json.RawMessage(user))\n\t}\n\treturn usersJson, nil\n}\n\nfunc (s *InboundService) addUsers(db *gorm.DB, inboundJson []byte, inboundId uint, inboundType string) ([]byte, error) {\n\tif !s.hasUser(inboundType) {\n\t\treturn inboundJson, nil\n\t}\n\n\tvar inbound map[string]interface{}\n\terr := json.Unmarshal(inboundJson, &inbound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcondition := fmt.Sprintf(\"%d IN (SELECT json_each.value FROM json_each(clients.inbounds))\", inboundId)\n\tinbound[\"users\"], err = s.fetchUsers(db, inboundType, condition, inbound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(inbound)\n}\n\nfunc (s *InboundService) initUsers(db *gorm.DB, inboundJson []byte, clientIds string, inboundType string) ([]byte, error) {\n\tClientIds := strings.Split(clientIds, \",\")\n\tif len(ClientIds) == 0 {\n\t\treturn inboundJson, nil\n\t}\n\n\tif !s.hasUser(inboundType) {\n\t\treturn inboundJson, nil\n\t}\n\n\tvar inbound map[string]interface{}\n\terr := json.Unmarshal(inboundJson, &inbound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcondition := fmt.Sprintf(\"id IN (%s)\", strings.Join(ClientIds, \",\"))\n\tinbound[\"users\"], err = s.fetchUsers(db, inboundType, condition, inbound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(inbound)\n}\n\nfunc (s *InboundService) RestartInbounds(tx *gorm.DB, ids []uint) error {\n\tif !corePtr.IsRunning() {\n\t\treturn nil\n\t}\n\tvar inbounds []*model.Inbound\n\terr := tx.Model(model.Inbound{}).Preload(\"Tls\").Where(\"id in ?\", ids).Find(&inbounds).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, inbound := range inbounds {\n\t\terr = corePtr.RemoveInbound(inbound.Tag)\n\t\tif err != nil && err != os.ErrInvalid {\n\t\t\treturn err\n\t\t}\n\t\t// Close all existing connections\n\t\tcorePtr.GetInstance().ConnTracker().CloseConnByInbound(inbound.Tag)\n\n\t\tinboundConfig, err := inbound.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinboundConfig, err = s.addUsers(tx, inboundConfig, inbound.Id, inbound.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = corePtr.AddInbound(inboundConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/outbounds.go",
    "content": "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/database/model\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype OutboundService struct{}\n\nfunc (o *OutboundService) GetAll() (*[]map[string]interface{}, error) {\n\tdb := database.GetDB()\n\toutbounds := []*model.Outbound{}\n\terr := db.Model(model.Outbound{}).Scan(&outbounds).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []map[string]interface{}\n\tfor _, outbound := range outbounds {\n\t\toutData := map[string]interface{}{\n\t\t\t\"id\":   outbound.Id,\n\t\t\t\"type\": outbound.Type,\n\t\t\t\"tag\":  outbound.Tag,\n\t\t}\n\t\tif outbound.Options != nil {\n\t\t\tvar restFields map[string]json.RawMessage\n\t\t\tif err := json.Unmarshal(outbound.Options, &restFields); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range restFields {\n\t\t\t\toutData[k] = v\n\t\t\t}\n\t\t}\n\t\tdata = append(data, outData)\n\t}\n\treturn &data, nil\n}\n\nfunc (o *OutboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error) {\n\tvar outboundsJson []json.RawMessage\n\tvar outbounds []*model.Outbound\n\terr := db.Model(model.Outbound{}).Scan(&outbounds).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, outbound := range outbounds {\n\t\toutboundJson, err := outbound.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toutboundsJson = append(outboundsJson, outboundJson)\n\t}\n\treturn outboundsJson, nil\n}\n\nfunc (s *OutboundService) Save(tx *gorm.DB, act string, data json.RawMessage) error {\n\tvar err error\n\n\tswitch act {\n\tcase \"new\", \"edit\":\n\t\tvar outbound model.Outbound\n\t\terr = outbound.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif corePtr.IsRunning() {\n\t\t\tconfigData, err := outbound.MarshalJSON()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif act == \"edit\" {\n\t\t\t\tvar oldTag string\n\t\t\t\terr = tx.Model(model.Outbound{}).Select(\"tag\").Where(\"id = ?\", outbound.Id).Find(&oldTag).Error\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = corePtr.RemoveOutbound(oldTag)\n\t\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = corePtr.AddOutbound(configData)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = tx.Save(&outbound).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"del\":\n\t\tvar tag string\n\t\terr = json.Unmarshal(data, &tag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif corePtr.IsRunning() {\n\t\t\terr = corePtr.RemoveOutbound(tag)\n\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\terr = tx.Where(\"tag = ?\", tag).Delete(model.Outbound{}).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn common.NewErrorf(\"unknown action: %s\", act)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/panel.go",
    "content": "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 struct {\n}\n\nfunc (s *PanelService) RestartPanel(delay time.Duration) error {\n\tp, err := os.FindProcess(syscall.Getpid())\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\ttime.Sleep(delay)\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\terr = p.Kill()\n\t\t} else {\n\t\t\terr = p.Signal(syscall.SIGHUP)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.Error(\"send signal SIGHUP failed:\", err)\n\t\t}\n\t}()\n\treturn nil\n}\n"
  },
  {
    "path": "service/server.go",
    "content": "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/config\"\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\n\t\"github.com/sagernet/sing-box/common/tls\"\n\t\"github.com/shirou/gopsutil/v4/cpu\"\n\t\"github.com/shirou/gopsutil/v4/disk\"\n\t\"github.com/shirou/gopsutil/v4/host\"\n\t\"github.com/shirou/gopsutil/v4/mem\"\n\t\"github.com/shirou/gopsutil/v4/net\"\n\t\"golang.zx2c4.com/wireguard/wgctrl/wgtypes\"\n)\n\ntype ServerService struct{}\n\nfunc (s *ServerService) GetStatus(request string) *map[string]interface{} {\n\tstatus := make(map[string]interface{}, 0)\n\trequests := strings.Split(request, \",\")\n\tfor _, req := range requests {\n\t\tswitch req {\n\t\tcase \"cpu\":\n\t\t\tstatus[\"cpu\"] = s.GetCpuPercent()\n\t\tcase \"mem\":\n\t\t\tstatus[\"mem\"] = s.GetMemInfo()\n\t\tcase \"dsk\":\n\t\t\tstatus[\"dsk\"] = s.GetDiskInfo()\n\t\tcase \"dio\":\n\t\t\tstatus[\"dio\"] = s.GetDiskIO()\n\t\tcase \"swp\":\n\t\t\tstatus[\"swp\"] = s.GetSwapInfo()\n\t\tcase \"net\":\n\t\t\tstatus[\"net\"] = s.GetNetInfo()\n\t\tcase \"sys\":\n\t\t\tstatus[\"sys\"] = s.GetSystemInfo()\n\t\tcase \"sbd\":\n\t\t\tstatus[\"sbd\"] = s.GetSingboxInfo()\n\t\tcase \"db\":\n\t\t\tstatus[\"db\"] = s.GetDatabaseInfo()\n\t\t}\n\t}\n\treturn &status\n}\n\nfunc (s *ServerService) GetCpuPercent() float64 {\n\tpercents, err := cpu.Percent(0, false)\n\tif err != nil {\n\t\tlogger.Warning(\"get cpu percent failed:\", err)\n\t\treturn 0\n\t} else {\n\t\treturn percents[0]\n\t}\n}\n\nfunc (s *ServerService) GetMemInfo() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tmemInfo, err := mem.VirtualMemory()\n\tif err != nil {\n\t\tlogger.Warning(\"get virtual memory failed:\", err)\n\t} else {\n\t\tinfo[\"current\"] = memInfo.Used\n\t\tinfo[\"total\"] = memInfo.Total\n\t}\n\treturn info\n}\n\nfunc (s *ServerService) GetDiskInfo() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tdiskInfo, err := disk.Usage(\"/\")\n\tif err != nil {\n\t\tlogger.Warning(\"get disk usage failed:\", err)\n\t} else {\n\t\tinfo[\"current\"] = diskInfo.Used\n\t\tinfo[\"total\"] = diskInfo.Total\n\t}\n\treturn info\n}\n\nfunc (s *ServerService) GetDiskIO() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tioStats, err := disk.IOCounters()\n\tif err != nil {\n\t\tlogger.Warning(\"get disk io counters failed:\", err)\n\t} else if len(ioStats) > 0 {\n\t\tinfoR, infoW := uint64(0), uint64(0)\n\t\tfor _, ioStat := range ioStats {\n\t\t\tinfoR += ioStat.ReadBytes\n\t\t\tinfoW += ioStat.WriteBytes\n\t\t}\n\t\tinfo[\"read\"] = infoR\n\t\tinfo[\"write\"] = infoW\n\t} else {\n\t\tlogger.Warning(\"can not find disk io counters\")\n\t}\n\treturn info\n}\n\nfunc (s *ServerService) GetSwapInfo() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tswapInfo, err := mem.SwapMemory()\n\tif err != nil {\n\t\tlogger.Warning(\"get swap memory failed:\", err)\n\t} else {\n\t\tinfo[\"current\"] = swapInfo.Used\n\t\tinfo[\"total\"] = swapInfo.Total\n\t}\n\treturn info\n}\n\nfunc (s *ServerService) GetNetInfo() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tioStats, err := net.IOCounters(false)\n\tif err != nil {\n\t\tlogger.Warning(\"get io counters failed:\", err)\n\t} else if len(ioStats) > 0 {\n\t\tioStat := ioStats[0]\n\t\tinfo[\"sent\"] = ioStat.BytesSent\n\t\tinfo[\"recv\"] = ioStat.BytesRecv\n\t\tinfo[\"psent\"] = ioStat.PacketsSent\n\t\tinfo[\"precv\"] = ioStat.PacketsRecv\n\t} else {\n\t\tlogger.Warning(\"can not find io counters\")\n\t}\n\treturn info\n}\n\nfunc (s *ServerService) GetSingboxInfo() map[string]interface{} {\n\tvar rtm runtime.MemStats\n\truntime.ReadMemStats(&rtm)\n\tisRunning := corePtr.IsRunning()\n\tuptime := uint32(0)\n\tif isRunning {\n\t\tuptime = corePtr.GetInstance().Uptime()\n\t}\n\treturn map[string]interface{}{\n\t\t\"running\": isRunning,\n\t\t\"stats\": map[string]interface{}{\n\t\t\t\"NumGoroutine\": uint32(runtime.NumGoroutine()),\n\t\t\t\"Alloc\":        rtm.Alloc,\n\t\t\t\"Uptime\":       uptime,\n\t\t},\n\t}\n}\n\nfunc (s *ServerService) GetSystemInfo() map[string]interface{} {\n\tinfo := make(map[string]interface{}, 0)\n\tvar rtm runtime.MemStats\n\truntime.ReadMemStats(&rtm)\n\n\tinfo[\"appMem\"] = rtm.Sys\n\tinfo[\"appThreads\"] = uint32(runtime.NumGoroutine())\n\tcpuInfo, err := cpu.Info()\n\tif err == nil {\n\t\tinfo[\"cpuType\"] = cpuInfo[0].ModelName\n\t}\n\tinfo[\"cpuCount\"] = runtime.NumCPU()\n\tinfo[\"hostName\"], _ = os.Hostname()\n\tinfo[\"appVersion\"] = config.GetVersion()\n\tipv4 := make([]string, 0)\n\tipv6 := make([]string, 0)\n\t// get ip address\n\tnetInterfaces, _ := net.Interfaces()\n\tfor i := 0; i < len(netInterfaces); i++ {\n\t\tif len(netInterfaces[i].Flags) > 2 && netInterfaces[i].Flags[0] == \"up\" && netInterfaces[i].Flags[1] != \"loopback\" {\n\t\t\taddrs := netInterfaces[i].Addrs\n\n\t\t\tfor _, address := range addrs {\n\t\t\t\tif strings.Contains(address.Addr, \".\") {\n\t\t\t\t\tipv4 = append(ipv4, address.Addr)\n\t\t\t\t} else if address.Addr[0:6] != \"fe80::\" {\n\t\t\t\t\tipv6 = append(ipv6, address.Addr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tinfo[\"ipv4\"] = ipv4\n\tinfo[\"ipv6\"] = ipv6\n\tinfo[\"bootTime\"], _ = host.BootTime()\n\n\treturn info\n}\n\nfunc (s *ServerService) GetLogs(count string, level string) []string {\n\tc, err := strconv.Atoi(count)\n\tif err != nil {\n\t\tc = 10\n\t}\n\treturn logger.GetLogs(c, level)\n}\n\nfunc (s *ServerService) GenKeypair(keyType string, options string) []string {\n\tif len(keyType) == 0 {\n\t\treturn []string{\"No keypair to generate\"}\n\t}\n\n\tswitch keyType {\n\tcase \"ech\":\n\t\treturn s.generateECHKeyPair(options)\n\tcase \"tls\":\n\t\treturn s.generateTLSKeyPair(options)\n\tcase \"reality\":\n\t\treturn s.generateRealityKeyPair()\n\tcase \"wireguard\":\n\t\treturn s.generateWireGuardKey(options)\n\t}\n\n\treturn []string{\"Failed to generate keypair\"}\n}\n\nfunc (s *ServerService) generateECHKeyPair(serverName string) []string {\n\tconfigPem, keyPem, err := tls.ECHKeygenDefault(serverName)\n\tif err != nil {\n\t\treturn []string{\"Failed to generate ECH keypair: \", err.Error()}\n\t}\n\treturn append(strings.Split(configPem, \"\\n\"), strings.Split(keyPem, \"\\n\")...)\n}\n\nfunc (s *ServerService) generateTLSKeyPair(serverName string) []string {\n\tprivateKeyPem, publicKeyPem, err := tls.GenerateCertificate(nil, nil, time.Now, serverName, time.Now().AddDate(0, 12, 0))\n\tif err != nil {\n\t\treturn []string{\"Failed to generate TLS keypair: \", err.Error()}\n\t}\n\treturn append(strings.Split(string(privateKeyPem), \"\\n\"), strings.Split(string(publicKeyPem), \"\\n\")...)\n}\n\nfunc (s *ServerService) generateRealityKeyPair() []string {\n\tprivateKey, err := wgtypes.GeneratePrivateKey()\n\tif err != nil {\n\t\treturn []string{\"Failed to generate Reality keypair: \", err.Error()}\n\t}\n\tpublicKey := privateKey.PublicKey()\n\treturn []string{\"PrivateKey: \" + base64.RawURLEncoding.EncodeToString(privateKey[:]), \"PublicKey: \" + base64.RawURLEncoding.EncodeToString(publicKey[:])}\n}\n\nfunc (s *ServerService) generateWireGuardKey(pk string) []string {\n\tif len(pk) > 0 {\n\t\tkey, _ := wgtypes.ParseKey(pk)\n\t\treturn []string{key.PublicKey().String()}\n\t}\n\twgKeys, err := wgtypes.GeneratePrivateKey()\n\tif err != nil {\n\t\treturn []string{\"Failed to generate wireguard keypair: \", err.Error()}\n\t}\n\treturn []string{\"PrivateKey: \" + wgKeys.String(), \"PublicKey: \" + wgKeys.PublicKey().String()}\n}\n\nfunc (s *ServerService) GetDatabaseInfo() map[string]int64 {\n\tinfo := make(map[string]int64, 0)\n\tdb := database.GetDB()\n\tif db == nil {\n\t\treturn nil\n\t}\n\n\tvar clientsCount, inboundsCount, outboundsCount, servicesCount, endpointsCount, clientUp, clientDown int64\n\n\tdb.Model(&model.Client{}).Count(&clientsCount)\n\tdb.Model(&model.Inbound{}).Count(&inboundsCount)\n\tdb.Model(&model.Outbound{}).Count(&outboundsCount)\n\tdb.Model(&model.Service{}).Count(&servicesCount)\n\tdb.Model(&model.Endpoint{}).Count(&endpointsCount)\n\tdb.Model(&model.Client{}).Select(\"COALESCE(SUM(up+total_up),0)\").Scan(&clientUp)\n\tdb.Model(&model.Client{}).Select(\"COALESCE(SUM(down+total_down),0)\").Scan(&clientDown)\n\n\tinfo[\"clients\"] = clientsCount\n\tinfo[\"inbounds\"] = inboundsCount\n\tinfo[\"outbounds\"] = outboundsCount\n\tinfo[\"services\"] = servicesCount\n\tinfo[\"endpoints\"] = endpointsCount\n\tinfo[\"clientUp\"] = clientUp\n\tinfo[\"clientDown\"] = clientDown\n\n\treturn info\n}\n"
  },
  {
    "path": "service/services.go",
    "content": "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/database/model\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype ServicesService struct{}\n\nfunc (s *ServicesService) GetAll() (*[]map[string]interface{}, error) {\n\tdb := database.GetDB()\n\tservices := []model.Service{}\n\terr := db.Model(model.Service{}).Scan(&services).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []map[string]interface{}\n\tfor _, srv := range services {\n\t\tsrvData := map[string]interface{}{\n\t\t\t\"id\":     srv.Id,\n\t\t\t\"type\":   srv.Type,\n\t\t\t\"tag\":    srv.Tag,\n\t\t\t\"tls_id\": srv.TlsId,\n\t\t}\n\t\tif srv.Options != nil {\n\t\t\tvar restFields map[string]json.RawMessage\n\t\t\tif err := json.Unmarshal(srv.Options, &restFields); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range restFields {\n\t\t\t\tsrvData[k] = v\n\t\t\t}\n\t\t}\n\n\t\tdata = append(data, srvData)\n\t}\n\treturn &data, nil\n}\n\nfunc (s *ServicesService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error) {\n\tvar servicesJson []json.RawMessage\n\tvar services []*model.Service\n\terr := db.Model(model.Service{}).Preload(\"Tls\").Find(&services).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, srv := range services {\n\t\tsrvJson, err := srv.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservicesJson = append(servicesJson, srvJson)\n\t}\n\treturn servicesJson, nil\n}\n\nfunc (s *ServicesService) Save(tx *gorm.DB, act string, data json.RawMessage) error {\n\tvar err error\n\n\tswitch act {\n\tcase \"new\", \"edit\":\n\t\tvar srv model.Service\n\t\terr = srv.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif srv.TlsId > 0 {\n\t\t\terr = tx.Model(model.Tls{}).Where(\"id = ?\", srv.TlsId).Find(&srv.Tls).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif corePtr.IsRunning() {\n\t\t\tconfigData, err := srv.MarshalJSON()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif act == \"edit\" {\n\t\t\t\tvar oldTag string\n\t\t\t\terr = tx.Model(model.Service{}).Select(\"tag\").Where(\"id = ?\", srv.Id).Find(&oldTag).Error\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = corePtr.RemoveService(oldTag)\n\t\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = corePtr.AddService(configData)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = tx.Save(&srv).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"del\":\n\t\tvar tag string\n\t\terr = json.Unmarshal(data, &tag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif corePtr.IsRunning() {\n\t\t\terr = corePtr.RemoveService(tag)\n\t\t\tif err != nil && err != os.ErrInvalid {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\terr = tx.Where(\"tag = ?\", tag).Delete(model.Service{}).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn common.NewErrorf(\"unknown action: %s\", act)\n\t}\n\treturn nil\n}\n\nfunc (s *ServicesService) RestartServices(tx *gorm.DB, ids []uint) error {\n\tif !corePtr.IsRunning() {\n\t\treturn nil\n\t}\n\tvar services []*model.Service\n\terr := tx.Model(model.Service{}).Preload(\"Tls\").Where(\"id in ?\", ids).Find(&services).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, srv := range services {\n\t\terr = corePtr.RemoveService(srv.Tag)\n\t\tif err != nil && err != os.ErrInvalid {\n\t\t\treturn err\n\t\t}\n\t\tsrvConfig, err := srv.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = corePtr.AddService(srvConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/setting.go",
    "content": "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/config\"\n\t\"github.com/alireza0/s-ui/database\"\n\t\"github.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\nvar defaultConfig = `{\n  \"log\": {\n    \"level\": \"info\"\n  },\n  \"dns\": {\n    \"servers\": [],\n    \"rules\": []\n  },\n  \"route\": {\n    \"rules\": [\n\t\t  {\n        \"action\": \"sniff\"\n      },\n      {\n        \"protocol\": [\n          \"dns\"\n        ],\n        \"action\": \"hijack-dns\"\n      }\n    ]\n  },\n  \"experimental\": {}\n}`\n\nvar defaultValueMap = map[string]string{\n\t\"webListen\":     \"\",\n\t\"webDomain\":     \"\",\n\t\"webPort\":       \"2095\",\n\t\"secret\":        common.Random(32),\n\t\"webCertFile\":   \"\",\n\t\"webKeyFile\":    \"\",\n\t\"webPath\":       \"/app/\",\n\t\"webURI\":        \"\",\n\t\"sessionMaxAge\": \"0\",\n\t\"trafficAge\":    \"30\",\n\t\"timeLocation\":  \"Asia/Tehran\",\n\t\"subListen\":     \"\",\n\t\"subPort\":       \"2096\",\n\t\"subPath\":       \"/sub/\",\n\t\"subDomain\":     \"\",\n\t\"subCertFile\":   \"\",\n\t\"subKeyFile\":    \"\",\n\t\"subUpdates\":    \"12\",\n\t\"subEncode\":     \"true\",\n\t\"subShowInfo\":   \"false\",\n\t\"subURI\":        \"\",\n\t\"subJsonExt\":    \"\",\n\t\"subClashExt\":   \"\",\n\t\"config\":        defaultConfig,\n\t\"version\":       config.GetVersion(),\n}\n\ntype SettingService struct {\n}\n\nfunc (s *SettingService) GetAllSetting() (*map[string]string, error) {\n\tdb := database.GetDB()\n\tsettings := make([]*model.Setting, 0)\n\terr := db.Model(model.Setting{}).Find(&settings).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tallSetting := map[string]string{}\n\n\tfor _, setting := range settings {\n\t\tallSetting[setting.Key] = setting.Value\n\t}\n\n\tfor key, defaultValue := range defaultValueMap {\n\t\tif _, exists := allSetting[key]; !exists {\n\t\t\terr = s.saveSetting(key, defaultValue)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tallSetting[key] = defaultValue\n\t\t}\n\t}\n\n\t// Due to security principles\n\tdelete(allSetting, \"secret\")\n\tdelete(allSetting, \"config\")\n\tdelete(allSetting, \"version\")\n\n\treturn &allSetting, nil\n}\n\nfunc (s *SettingService) ResetSettings() error {\n\tdb := database.GetDB()\n\treturn db.Where(\"1 = 1\").Delete(model.Setting{}).Error\n}\n\nfunc (s *SettingService) getSetting(key string) (*model.Setting, error) {\n\tdb := database.GetDB()\n\tsetting := &model.Setting{}\n\terr := db.Model(model.Setting{}).Where(\"key = ?\", key).First(setting).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn setting, nil\n}\n\nfunc (s *SettingService) getString(key string) (string, error) {\n\tsetting, err := s.getSetting(key)\n\tif database.IsNotFound(err) {\n\t\tvalue, ok := defaultValueMap[key]\n\t\tif !ok {\n\t\t\treturn \"\", common.NewErrorf(\"key <%v> not in defaultValueMap\", key)\n\t\t}\n\t\treturn value, nil\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\treturn setting.Value, nil\n}\n\nfunc (s *SettingService) saveSetting(key string, value string) error {\n\tsetting, err := s.getSetting(key)\n\tdb := database.GetDB()\n\tif database.IsNotFound(err) {\n\t\treturn db.Create(&model.Setting{\n\t\t\tKey:   key,\n\t\t\tValue: value,\n\t\t}).Error\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tsetting.Key = key\n\tsetting.Value = value\n\treturn db.Save(setting).Error\n}\n\nfunc (s *SettingService) setString(key string, value string) error {\n\treturn s.saveSetting(key, value)\n}\n\nfunc (s *SettingService) getBool(key string) (bool, error) {\n\tstr, err := s.getString(key)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn strconv.ParseBool(str)\n}\n\n// func (s *SettingService) setBool(key string, value bool) error {\n// \treturn s.setString(key, strconv.FormatBool(value))\n// }\n\nfunc (s *SettingService) getInt(key string) (int, error) {\n\tstr, err := s.getString(key)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(str)\n}\n\nfunc (s *SettingService) setInt(key string, value int) error {\n\treturn s.setString(key, strconv.Itoa(value))\n}\nfunc (s *SettingService) GetListen() (string, error) {\n\treturn s.getString(\"webListen\")\n}\n\nfunc (s *SettingService) GetWebDomain() (string, error) {\n\treturn s.getString(\"webDomain\")\n}\n\nfunc (s *SettingService) GetPort() (int, error) {\n\treturn s.getInt(\"webPort\")\n}\n\nfunc (s *SettingService) SetPort(port int) error {\n\treturn s.setInt(\"webPort\", port)\n}\n\nfunc (s *SettingService) GetCertFile() (string, error) {\n\treturn s.getString(\"webCertFile\")\n}\n\nfunc (s *SettingService) GetKeyFile() (string, error) {\n\treturn s.getString(\"webKeyFile\")\n}\n\nfunc (s *SettingService) GetWebPath() (string, error) {\n\twebPath, err := s.getString(\"webPath\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !strings.HasPrefix(webPath, \"/\") {\n\t\twebPath = \"/\" + webPath\n\t}\n\tif !strings.HasSuffix(webPath, \"/\") {\n\t\twebPath += \"/\"\n\t}\n\treturn webPath, nil\n}\n\nfunc (s *SettingService) SetWebPath(webPath string) error {\n\tif !strings.HasPrefix(webPath, \"/\") {\n\t\twebPath = \"/\" + webPath\n\t}\n\tif !strings.HasSuffix(webPath, \"/\") {\n\t\twebPath += \"/\"\n\t}\n\treturn s.setString(\"webPath\", webPath)\n}\n\nfunc (s *SettingService) GetSecret() ([]byte, error) {\n\tsecret, err := s.getString(\"secret\")\n\tif secret == defaultValueMap[\"secret\"] {\n\t\terr := s.saveSetting(\"secret\", secret)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"save secret failed:\", err)\n\t\t}\n\t}\n\treturn []byte(secret), err\n}\n\nfunc (s *SettingService) GetSessionMaxAge() (int, error) {\n\treturn s.getInt(\"sessionMaxAge\")\n}\n\nfunc (s *SettingService) GetTrafficAge() (int, error) {\n\treturn s.getInt(\"trafficAge\")\n}\n\nfunc (s *SettingService) GetTimeLocation() (*time.Location, error) {\n\tl, err := s.getString(\"timeLocation\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tl = \"Local\"\n\t}\n\tlocation, err := time.LoadLocation(l)\n\tif err != nil {\n\t\tdefaultLocation := defaultValueMap[\"timeLocation\"]\n\t\tlogger.Errorf(\"location <%v> not exist, using default location: %v\", l, defaultLocation)\n\t\treturn time.LoadLocation(defaultLocation)\n\t}\n\treturn location, nil\n}\n\nfunc (s *SettingService) GetSubListen() (string, error) {\n\treturn s.getString(\"subListen\")\n}\n\nfunc (s *SettingService) GetSubPort() (int, error) {\n\treturn s.getInt(\"subPort\")\n}\n\nfunc (s *SettingService) SetSubPort(subPort int) error {\n\treturn s.setInt(\"subPort\", subPort)\n}\n\nfunc (s *SettingService) GetSubPath() (string, error) {\n\tsubPath, err := s.getString(\"subPath\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !strings.HasPrefix(subPath, \"/\") {\n\t\tsubPath = \"/\" + subPath\n\t}\n\tif !strings.HasSuffix(subPath, \"/\") {\n\t\tsubPath += \"/\"\n\t}\n\treturn subPath, nil\n}\n\nfunc (s *SettingService) SetSubPath(subPath string) error {\n\tif !strings.HasPrefix(subPath, \"/\") {\n\t\tsubPath = \"/\" + subPath\n\t}\n\tif !strings.HasSuffix(subPath, \"/\") {\n\t\tsubPath += \"/\"\n\t}\n\treturn s.setString(\"subPath\", subPath)\n}\n\nfunc (s *SettingService) GetSubDomain() (string, error) {\n\treturn s.getString(\"subDomain\")\n}\n\nfunc (s *SettingService) GetSubCertFile() (string, error) {\n\treturn s.getString(\"subCertFile\")\n}\n\nfunc (s *SettingService) GetSubKeyFile() (string, error) {\n\treturn s.getString(\"subKeyFile\")\n}\n\nfunc (s *SettingService) GetSubUpdates() (int, error) {\n\treturn s.getInt(\"subUpdates\")\n}\n\nfunc (s *SettingService) GetSubEncode() (bool, error) {\n\treturn s.getBool(\"subEncode\")\n}\n\nfunc (s *SettingService) GetSubShowInfo() (bool, error) {\n\treturn s.getBool(\"subShowInfo\")\n}\n\nfunc (s *SettingService) GetSubURI() (string, error) {\n\treturn s.getString(\"subURI\")\n}\n\nfunc (s *SettingService) GetFinalSubURI(host string) (string, error) {\n\tallSetting, err := s.GetAllSetting()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tSubURI := (*allSetting)[\"subURI\"]\n\tif SubURI != \"\" {\n\t\treturn SubURI, nil\n\t}\n\tprotocol := \"http\"\n\tif (*allSetting)[\"subKeyFile\"] != \"\" && (*allSetting)[\"subCertFile\"] != \"\" {\n\t\tprotocol = \"https\"\n\t}\n\tif (*allSetting)[\"subDomain\"] != \"\" {\n\t\thost = (*allSetting)[\"subDomain\"]\n\t}\n\tport := \":\" + (*allSetting)[\"subPort\"]\n\tif (port == \"80\" && protocol == \"http\") || (port == \"443\" && protocol == \"https\") {\n\t\tport = \"\"\n\t}\n\treturn protocol + \"://\" + host + port + (*allSetting)[\"subPath\"], nil\n}\n\nfunc (s *SettingService) GetConfig() (string, error) {\n\treturn s.getString(\"config\")\n}\n\nfunc (s *SettingService) SetConfig(config string) error {\n\treturn s.setString(\"config\", config)\n}\n\nfunc (s *SettingService) SaveConfig(tx *gorm.DB, config json.RawMessage) error {\n\tconfigs, err := json.MarshalIndent(config, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tx.Model(model.Setting{}).Where(\"key = ?\", \"config\").Update(\"value\", string(configs)).Error\n}\n\nfunc (s *SettingService) Save(tx *gorm.DB, data json.RawMessage) error {\n\tvar err error\n\tvar settings map[string]string\n\terr = json.Unmarshal(data, &settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor key, obj := range settings {\n\t\t// Secure file existence check\n\t\tif obj != \"\" && (key == \"webCertFile\" ||\n\t\t\tkey == \"webKeyFile\" ||\n\t\t\tkey == \"subCertFile\" ||\n\t\t\tkey == \"subKeyFile\") {\n\t\t\terr = s.fileExists(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn common.NewError(\" -> \", obj, \" is not exists\")\n\t\t\t}\n\t\t}\n\n\t\t// Correct Pathes start and ends with `/`\n\t\tif key == \"webPath\" ||\n\t\t\tkey == \"subPath\" {\n\t\t\tif !strings.HasPrefix(obj, \"/\") {\n\t\t\t\tobj = \"/\" + obj\n\t\t\t}\n\t\t\tif !strings.HasSuffix(obj, \"/\") {\n\t\t\t\tobj += \"/\"\n\t\t\t}\n\t\t}\n\n\t\t// Delete all stats if it is set to 0\n\t\tif key == \"trafficAge\" && obj == \"0\" {\n\t\t\terr = tx.Where(\"id > 0\").Delete(model.Stats{}).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\terr = tx.Model(model.Setting{}).Where(\"key = ?\", key).Update(\"value\", obj).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (s *SettingService) GetSubJsonExt() (string, error) {\n\treturn s.getString(\"subJsonExt\")\n}\n\nfunc (s *SettingService) GetSubClashExt() (string, error) {\n\treturn s.getString(\"subClashExt\")\n}\n\nfunc (s *SettingService) fileExists(path string) error {\n\t_, err := os.Stat(path)\n\treturn err\n}\n"
  },
  {
    "path": "service/stats.go",
    "content": "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/model\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype onlines struct {\n\tInbound  []string `json:\"inbound,omitempty\"`\n\tUser     []string `json:\"user,omitempty\"`\n\tOutbound []string `json:\"outbound,omitempty\"`\n}\n\nvar onlineResources = &onlines{}\n\ntype StatsService struct {\n}\n\nfunc (s *StatsService) SaveStats(enableTraffic bool) error {\n\tif !corePtr.IsRunning() {\n\t\treturn nil\n\t}\n\tstats := corePtr.GetInstance().StatsTracker().GetStats()\n\n\t// Reset onlines\n\tonlineResources.Inbound = nil\n\tonlineResources.Outbound = nil\n\tonlineResources.User = nil\n\n\tif len(*stats) == 0 {\n\t\treturn nil\n\t}\n\n\tvar err error\n\tdb := database.GetDB()\n\ttx := db.Begin()\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ttx.Commit()\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\tfor _, stat := range *stats {\n\t\tif stat.Resource == \"user\" {\n\t\t\tif stat.Direction {\n\t\t\t\terr = tx.Model(model.Client{}).Where(\"name = ?\", stat.Tag).\n\t\t\t\t\tUpdateColumn(\"up\", gorm.Expr(\"up + ?\", stat.Traffic)).Error\n\t\t\t} else {\n\t\t\t\terr = tx.Model(model.Client{}).Where(\"name = ?\", stat.Tag).\n\t\t\t\t\tUpdateColumn(\"down\", gorm.Expr(\"down + ?\", stat.Traffic)).Error\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif stat.Direction {\n\t\t\tswitch stat.Resource {\n\t\t\tcase \"inbound\":\n\t\t\t\tonlineResources.Inbound = append(onlineResources.Inbound, stat.Tag)\n\t\t\tcase \"outbound\":\n\t\t\t\tonlineResources.Outbound = append(onlineResources.Outbound, stat.Tag)\n\t\t\tcase \"user\":\n\t\t\t\tonlineResources.User = append(onlineResources.User, stat.Tag)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !enableTraffic {\n\t\treturn nil\n\t}\n\treturn tx.Create(&stats).Error\n}\n\nfunc (s *StatsService) GetStats(resource string, tag string, limit int) ([]model.Stats, error) {\n\tvar err error\n\tvar result []model.Stats\n\n\tcurrentTime := time.Now().Unix()\n\ttimeDiff := currentTime - (int64(limit) * 3600)\n\n\tdb := database.GetDB()\n\tresources := []string{resource}\n\tif resource == \"endpoint\" {\n\t\tresources = []string{\"inbound\", \"outbound\"}\n\t}\n\terr = db.Model(model.Stats{}).Where(\"resource in ? AND tag = ? AND date_time > ?\", resources, tag, timeDiff).Scan(&result).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = s.downsampleStats(result, 60) // 60 rows for 30 buckets\n\treturn result, nil\n}\n\n// downsampleStats reduces stats to maxRows rows.\n// Each bucket outputs two rows (direction false and true) with average Traffic.\nfunc (s *StatsService) downsampleStats(stats []model.Stats, maxRows int) []model.Stats {\n\tif len(stats) <= maxRows {\n\t\treturn stats\n\t}\n\tnumBuckets := int(maxRows / 2)\n\tsort.Slice(stats, func(i, j int) bool { return stats[i].DateTime < stats[j].DateTime })\n\ttimeMin, timeMax := stats[0].DateTime, stats[len(stats)-1].DateTime\n\tbucketSpan := (timeMax - timeMin) / int64(numBuckets)\n\tif bucketSpan == 0 {\n\t\tbucketSpan = 1\n\t}\n\tdownsampled := make([]model.Stats, 0, maxRows)\n\tfor i := 0; i < numBuckets; i++ {\n\t\tbucketStart := timeMin + int64(i)*bucketSpan\n\t\tbucketEnd := timeMin + int64(i+1)*bucketSpan\n\t\tif i == numBuckets-1 {\n\t\t\tbucketEnd = timeMax + 1\n\t\t}\n\t\tfor _, dir := range []bool{false, true} {\n\t\t\tvar sum int64\n\t\t\tvar count int\n\t\t\tfor _, r := range stats {\n\t\t\t\tif r.DateTime >= bucketStart && r.DateTime < bucketEnd && r.Direction == dir {\n\t\t\t\t\tsum += r.Traffic\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\t\t\tavg := int64(0)\n\t\t\tif count > 0 {\n\t\t\t\tavg = sum / int64(count)\n\t\t\t}\n\t\t\tdownsampled = append(downsampled, model.Stats{\n\t\t\t\tDateTime:  bucketStart,\n\t\t\t\tResource:  stats[0].Resource,\n\t\t\t\tTag:       stats[0].Tag,\n\t\t\t\tDirection: dir,\n\t\t\t\tTraffic:   avg,\n\t\t\t})\n\t\t}\n\t}\n\treturn downsampled\n}\n\nfunc (s *StatsService) GetOnlines() (onlines, error) {\n\treturn *onlineResources, nil\n}\nfunc (s *StatsService) DelOldStats(days int) error {\n\toldTime := time.Now().AddDate(0, 0, -(days)).Unix()\n\tdb := database.GetDB()\n\treturn db.Where(\"date_time < ?\", oldTime).Delete(model.Stats{}).Error\n}\n"
  },
  {
    "path": "service/tls.go",
    "content": "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/model\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"gorm.io/gorm\"\n)\n\ntype TlsService struct {\n\tInboundService\n\tServicesService\n}\n\nfunc (s *TlsService) GetAll() ([]model.Tls, error) {\n\tdb := database.GetDB()\n\ttlsConfig := []model.Tls{}\n\terr := db.Model(model.Tls{}).Scan(&tlsConfig).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tlsConfig, nil\n}\n\nfunc (s *TlsService) Save(tx *gorm.DB, action string, data json.RawMessage, hostname string) error {\n\tvar err error\n\n\tswitch action {\n\tcase \"new\", \"edit\":\n\t\tvar tls model.Tls\n\t\terr = json.Unmarshal(data, &tls)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = tx.Save(&tls).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif action == \"edit\" {\n\t\t\tvar inbounds []model.Inbound\n\t\t\terr = tx.Model(model.Inbound{}).Preload(\"Tls\").Where(\"tls_id = ?\", tls.Id).Find(&inbounds).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(inbounds) > 0 {\n\t\t\t\terr = s.ClientService.UpdateLinksByInboundChange(tx, &inbounds, hostname, \"\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tvar inboundIds []uint\n\t\t\t\tfor _, inbound := range inbounds {\n\t\t\t\t\tinboundIds = append(inboundIds, inbound.Id)\n\t\t\t\t}\n\t\t\t\terr = s.InboundService.UpdateOutJsons(tx, inboundIds, hostname)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn common.NewError(\"unable to update out_json of inbounds: \", err.Error())\n\t\t\t\t}\n\t\t\t\terr = s.InboundService.RestartInbounds(tx, inboundIds)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar serviceIds []uint\n\t\t\terr = tx.Model(model.Service{}).Where(\"tls_id = ?\", tls.Id).Scan(&serviceIds).Error\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(serviceIds) > 0 {\n\t\t\t\terr = s.ServicesService.RestartServices(tx, serviceIds)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase \"del\":\n\t\tvar id uint\n\t\terr = json.Unmarshal(data, &id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar inboundCount int64\n\t\terr = tx.Model(model.Inbound{}).Where(\"tls_id = ?\", id).Count(&inboundCount).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar serviceCount int64\n\t\terr = tx.Model(model.Service{}).Where(\"tls_id = ?\", id).Count(&serviceCount).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif inboundCount > 0 || serviceCount > 0 {\n\t\t\treturn common.NewError(\"tls in use\")\n\t\t}\n\t\terr = tx.Where(\"id = ?\", id).Delete(model.Tls{}).Error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "service/user.go",
    "content": "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/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n)\n\ntype UserService struct {\n}\n\nfunc (s *UserService) GetFirstUser() (*model.User, error) {\n\tdb := database.GetDB()\n\n\tuser := &model.User{}\n\terr := db.Model(model.User{}).\n\t\tFirst(user).\n\t\tError\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}\n\nfunc (s *UserService) UpdateFirstUser(username string, password string) error {\n\tif username == \"\" {\n\t\treturn common.NewError(\"username can not be empty\")\n\t} else if password == \"\" {\n\t\treturn common.NewError(\"password can not be empty\")\n\t}\n\tdb := database.GetDB()\n\tuser := &model.User{}\n\terr := db.Model(model.User{}).First(user).Error\n\tif database.IsNotFound(err) {\n\t\tuser.Username = username\n\t\tuser.Password = password\n\t\treturn db.Model(model.User{}).Create(user).Error\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tuser.Username = username\n\tuser.Password = password\n\treturn db.Save(user).Error\n}\n\nfunc (s *UserService) Login(username string, password string, remoteIP string) (string, error) {\n\tuser := s.CheckUser(username, password, remoteIP)\n\tif user == nil {\n\t\treturn \"\", common.NewError(\"wrong user or password! IP: \", remoteIP)\n\t}\n\treturn user.Username, nil\n}\n\nfunc (s *UserService) CheckUser(username string, password string, remoteIP string) *model.User {\n\tdb := database.GetDB()\n\n\tuser := &model.User{}\n\terr := db.Model(model.User{}).\n\t\tWhere(\"username = ? and password = ?\", username, password).\n\t\tFirst(user).\n\t\tError\n\tif database.IsNotFound(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\tlogger.Warning(\"check user err:\", err, \" IP: \", remoteIP)\n\t\treturn nil\n\t}\n\n\tlastLoginTxt := time.Now().Format(\"2006-01-02 15:04:05\") + \" \" + remoteIP\n\terr = db.Model(model.User{}).\n\t\tWhere(\"username = ?\", username).\n\t\tUpdate(\"last_logins\", &lastLoginTxt).Error\n\tif err != nil {\n\t\tlogger.Warning(\"unable to log login data\", err)\n\t}\n\treturn user\n}\n\nfunc (s *UserService) GetUsers() (*[]model.User, error) {\n\tvar users []model.User\n\tdb := database.GetDB()\n\terr := db.Model(model.User{}).Select(\"id,username,last_logins\").Scan(&users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &users, nil\n}\n\nfunc (s *UserService) ChangePass(id string, oldPass string, newUser string, newPass string) error {\n\tdb := database.GetDB()\n\tuser := &model.User{}\n\terr := db.Model(model.User{}).Where(\"id = ? AND password = ?\", id, oldPass).First(user).Error\n\tif err != nil || database.IsNotFound(err) {\n\t\treturn err\n\t}\n\tuser.Username = newUser\n\tuser.Password = newPass\n\treturn db.Save(user).Error\n}\n\nfunc (s *UserService) LoadTokens() ([]byte, error) {\n\tdb := database.GetDB()\n\tvar tokens []model.Tokens\n\terr := db.Model(model.Tokens{}).Preload(\"User\").Where(\"expiry == 0 or expiry > ?\", time.Now().Unix()).Find(&tokens).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result []map[string]interface{}\n\tfor _, t := range tokens {\n\t\tresult = append(result, map[string]interface{}{\n\t\t\t\"token\":    t.Token,\n\t\t\t\"expiry\":   t.Expiry,\n\t\t\t\"username\": t.User.Username,\n\t\t})\n\t}\n\tjsonResult, _ := json.MarshalIndent(result, \"\", \"  \")\n\treturn jsonResult, nil\n}\n\nfunc (s *UserService) GetUserTokens(username string) (*[]model.Tokens, error) {\n\tdb := database.GetDB()\n\tvar token []model.Tokens\n\terr := db.Model(model.Tokens{}).Select(\"id,desc,'****' as token,expiry,user_id\").Where(\"user_id = (select id from users where username = ?)\", username).Find(&token).Error\n\tif err != nil && !database.IsNotFound(err) {\n\t\tprintln(err.Error())\n\t\treturn nil, err\n\t}\n\treturn &token, nil\n}\n\nfunc (s *UserService) AddToken(username string, expiry int64, desc string) (string, error) {\n\tdb := database.GetDB()\n\tvar userId uint\n\terr := db.Model(model.User{}).Where(\"username = ?\", username).Select(\"id\").Scan(&userId).Error\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif expiry > 0 {\n\t\texpiry = expiry*86400 + time.Now().Unix()\n\t}\n\ttoken := &model.Tokens{\n\t\tToken:  common.Random(32),\n\t\tDesc:   desc,\n\t\tExpiry: expiry,\n\t\tUserId: userId,\n\t}\n\terr = db.Create(token).Error\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn token.Token, nil\n}\n\nfunc (s *UserService) DeleteToken(id string) error {\n\tdb := database.GetDB()\n\treturn db.Model(model.Tokens{}).Where(\"id = ?\", id).Delete(&model.Tokens{}).Error\n}\n"
  },
  {
    "path": "service/warp.go",
    "content": "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\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/util/common\"\n\n\t\"golang.zx2c4.com/wireguard/wgctrl/wgtypes\"\n)\n\ntype WarpService struct{}\n\nfunc (s *WarpService) getWarpInfo(deviceId string, accessToken string) ([]byte, error) {\n\turl := fmt.Sprintf(\"https://api.cloudflareclient.com/v0a2158/reg/%s\", deviceId)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+accessToken)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil || resp.StatusCode != 200 {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuffer := bytes.NewBuffer(make([]byte, 8192))\n\tbuffer.Reset()\n\t_, err = buffer.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}\n\nfunc (s *WarpService) RegisterWarp(ep *model.Endpoint) error {\n\ttos := time.Now().UTC().Format(\"2006-01-02T15:04:05.000Z\")\n\tprivateKey, _ := wgtypes.GenerateKey()\n\tpublicKey := privateKey.PublicKey().String()\n\thostName, _ := os.Hostname()\n\n\tdata := fmt.Sprintf(`{\"key\":\"%s\",\"tos\":\"%s\",\"type\": \"PC\",\"model\": \"s-ui\", \"name\": \"%s\"}`, publicKey, tos, hostName)\n\turl := \"https://api.cloudflareclient.com/v0a2158/reg\"\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer([]byte(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"CF-Client-Version\", \"a-7.21-0721\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil || resp.StatusCode != 200 {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbuffer := bytes.NewBuffer(make([]byte, 8192))\n\tbuffer.Reset()\n\t_, err = buffer.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rspData map[string]interface{}\n\terr = json.Unmarshal(buffer.Bytes(), &rspData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdeviceId := rspData[\"id\"].(string)\n\ttoken := rspData[\"token\"].(string)\n\tlicense, ok := rspData[\"account\"].(map[string]interface{})[\"license\"].(string)\n\tif !ok {\n\t\tlogger.Debug(\"Error accessing license value.\")\n\t\treturn err\n\t}\n\n\twarpInfo, err := s.getWarpInfo(deviceId, token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar warpDetails map[string]interface{}\n\terr = json.Unmarshal(warpInfo, &warpDetails)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twarpConfig, _ := warpDetails[\"config\"].(map[string]interface{})\n\tclientId, _ := warpConfig[\"client_id\"].(string)\n\treserved := s.getReserved(clientId)\n\tinterfaceConfig, _ := warpConfig[\"interface\"].(map[string]interface{})\n\taddresses, _ := interfaceConfig[\"addresses\"].(map[string]interface{})\n\tv4, _ := addresses[\"v4\"].(string)\n\tv6, _ := addresses[\"v6\"].(string)\n\tpeer, _ := warpConfig[\"peers\"].([]interface{})[0].(map[string]interface{})\n\tpeerEndpoint, _ := peer[\"endpoint\"].(map[string]interface{})[\"host\"].(string)\n\tpeerEpAddress, peerEpPort, err := net.SplitHostPort(peerEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpeerPublicKey, _ := peer[\"public_key\"].(string)\n\tpeerPort, _ := strconv.Atoi(peerEpPort)\n\n\tpeers := []map[string]interface{}{\n\t\t{\n\t\t\t\"address\":     peerEpAddress,\n\t\t\t\"port\":        peerPort,\n\t\t\t\"public_key\":  peerPublicKey,\n\t\t\t\"allowed_ips\": []string{\"0.0.0.0/0\", \"::/0\"},\n\t\t\t\"reserved\":    reserved,\n\t\t},\n\t}\n\n\twarpData := map[string]interface{}{\n\t\t\"access_token\": token,\n\t\t\"device_id\":    deviceId,\n\t\t\"license_key\":  license,\n\t}\n\n\tep.Ext, err = json.MarshalIndent(warpData, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar epOptions map[string]interface{}\n\terr = json.Unmarshal(ep.Options, &epOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\tepOptions[\"private_key\"] = privateKey.String()\n\tepOptions[\"address\"] = []string{fmt.Sprintf(\"%s/32\", v4), fmt.Sprintf(\"%s/128\", v6)}\n\tepOptions[\"listen_port\"] = 0\n\tepOptions[\"peers\"] = peers\n\n\tep.Options, err = json.MarshalIndent(epOptions, \"\", \"  \")\n\treturn err\n}\n\nfunc (s *WarpService) getReserved(clientID string) []int {\n\tvar reserved []int\n\tdecoded, err := base64.StdEncoding.DecodeString(clientID)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\thexString := \"\"\n\tfor _, char := range decoded {\n\t\thex := fmt.Sprintf(\"%02x\", char)\n\t\thexString += hex\n\t}\n\n\tfor i := 0; i < len(hexString); i += 2 {\n\t\thexByte := hexString[i : i+2]\n\t\tdecValue, err := strconv.ParseInt(hexByte, 16, 32)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\treserved = append(reserved, int(decValue))\n\t}\n\n\treturn reserved\n}\n\nfunc (s *WarpService) SetWarpLicense(old_license string, ep *model.Endpoint) error {\n\tvar warpData map[string]string\n\terr := json.Unmarshal(ep.Ext, &warpData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif warpData[\"license_key\"] == old_license {\n\t\treturn nil\n\t}\n\n\turl := fmt.Sprintf(\"https://api.cloudflareclient.com/v0a2158/reg/%s/account\", warpData[\"device_id\"])\n\tdata := fmt.Sprintf(`{\"license\": \"%s\"}`, warpData[\"license_key\"])\n\n\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBuffer([]byte(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+warpData[\"access_token\"])\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbuffer := bytes.NewBuffer(make([]byte, 8192))\n\tbuffer.Reset()\n\t_, err = buffer.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar response map[string]interface{}\n\terr = json.Unmarshal(buffer.Bytes(), &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif success, ok := response[\"success\"].(bool); ok && success == false {\n\t\terrorArr, _ := response[\"errors\"].([]interface{})\n\t\terrorObj := errorArr[0].(map[string]interface{})\n\t\treturn common.NewError(errorObj[\"code\"], errorObj[\"message\"])\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "sub/clashService.go",
    "content": "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/alireza0/s-ui/util\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype ClashService struct {\n\tservice.SettingService\n\tJsonService\n\tLinkService\n}\n\nconst basicClashConfig = `mixed-port: 7890\nallow-lan: false\nmode: rule\nlog-level: info\nexternal-controller: 127.0.0.1:9090\ntun:\n  enable: true\n  stack: system\n  auto-route: true\n  auto-detect-interface: true\n  dns-hijack:\n    - any:53\ndns:\n  enable: true\n  ipv6: false\n  enhanced-mode: fake-ip\n  fake-ip-range: 198.18.0.1/16\n  default-nameserver:\n    - 8.8.8.8\n    - 1.1.1.1\n  nameserver:\n    - https://doh.pub/dns-query\n    - https://1.0.0.1/dns-query\n  fallback:\n    - tcp://9.9.9.9:53\n  fake-ip-filter:\n    - \"*.lan\"\n    - localhost\n    - \"*.local\"\nrules:\n  - GEOIP,Private,DIRECT\n  - MATCH,Proxy\n`\n\nconst ProxyGroups = `- name: Proxy\n  type: select\n  proxies: []\n- name: Auto\n  type: url-test\n  proxies: []\n  url: http://www.gstatic.com/generate_204\n  interval: 300\n  tolerance: 50\n`\n\nfunc (s *ClashService) GetClash(subId string) (*string, []string, error) {\n\n\tclient, inDatas, err := s.getData(subId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\toutbounds, outTags, err := s.getOutbounds(client.Config, inDatas)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tlinks := s.LinkService.GetLinks(&client.Links, \"external\", \"\")\n\ttagNumEnable := 0\n\tif len(links) > 1 {\n\t\ttagNumEnable = 1\n\t}\n\tfor index, link := range links {\n\t\tjson, tag, err := util.GetOutbound(link, (index+1)*tagNumEnable)\n\t\tif err == nil && len(tag) > 0 {\n\t\t\t*outbounds = append(*outbounds, *json)\n\t\t\t*outTags = append(*outTags, tag)\n\t\t}\n\t}\n\n\tothersStr, err := s.getClashConfig()\n\tif err != nil || len(othersStr) == 0 {\n\t\tothersStr = basicClashConfig\n\t}\n\n\tresult, err := s.ConvertToClashMeta(outbounds)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tresultStr := othersStr + \"\\n\" + string(result)\n\n\tupdateInterval, _ := s.SettingService.GetSubUpdates()\n\theaders := util.GetHeaders(client, updateInterval)\n\n\treturn &resultStr, headers, nil\n}\n\nfunc (s *ClashService) getClashConfig() (string, error) {\n\tsubClashExt, err := s.SettingService.GetSubClashExt()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn subClashExt, nil\n}\n\nfunc (s *ClashService) ConvertToClashMeta(outbounds *[]map[string]interface{}) ([]byte, error) {\n\tvar proxies []interface{}\n\tproxyTags := make([]string, 0)\n\tfor _, obMap := range *outbounds {\n\n\t\tt, _ := obMap[\"type\"].(string)\n\t\tif t == \"selector\" || t == \"urltest\" || t == \"direct\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tproxy := make(map[string]interface{})\n\t\tproxy[\"name\"] = obMap[\"tag\"]\n\t\tproxy[\"type\"] = t\n\n\t\tserver, _ := obMap[\"server\"].(string)\n\t\tif len(server) > 0 && strings.Contains(server, \":\") && !strings.Contains(server, \".\") && !(strings.HasPrefix(server, \"[\") && strings.HasSuffix(server, \"]\")) {\n\t\t\tserver = \"'[\" + server + \"]'\"\n\t\t}\n\t\tproxy[\"server\"] = server\n\n\t\tproxy[\"port\"] = obMap[\"server_port\"]\n\n\t\tswitch t {\n\t\tcase \"vmess\", \"vless\", \"tuic\":\n\t\t\tproxy[\"uuid\"] = obMap[\"uuid\"]\n\t\t\tif t == \"vmess\" {\n\t\t\t\tif alterId, ok := obMap[\"alter_id\"].(float64); ok {\n\t\t\t\t\tproxy[\"alterId\"] = int(alterId)\n\t\t\t\t} else {\n\t\t\t\t\tproxy[\"alterId\"] = 0\n\t\t\t\t}\n\t\t\t\tproxy[\"cipher\"] = \"auto\"\n\t\t\t}\n\t\t\tif t == \"vless\" {\n\t\t\t\tif flow, ok := obMap[\"flow\"].(string); ok {\n\t\t\t\t\tproxy[\"flow\"] = flow\n\t\t\t\t}\n\t\t\t}\n\t\t\tif t == \"tuic\" {\n\t\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\t\t\tif congestion_control, ok := obMap[\"congestion_control\"].(string); ok {\n\t\t\t\t\tproxy[\"congestion-controller\"] = congestion_control\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"trojan\":\n\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\tcase \"socks\", \"http\":\n\t\t\tif t == \"socks\" {\n\t\t\t\tproxy[\"type\"] = \"socks5\"\n\t\t\t}\n\t\t\tproxy[\"username\"] = obMap[\"username\"]\n\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\tcase \"hysteria\", \"hysteria2\":\n\t\t\tif _, ok := obMap[\"up_mbps\"].(float64); ok {\n\t\t\t\tproxy[\"up\"] = obMap[\"up_mbps\"]\n\t\t\t} else {\n\t\t\t\tproxy[\"up\"] = 1000\n\t\t\t}\n\t\t\tif _, ok := obMap[\"down_mbps\"].(float64); ok {\n\t\t\t\tproxy[\"down\"] = obMap[\"down_mbps\"]\n\t\t\t} else {\n\t\t\t\tproxy[\"down\"] = 1000\n\t\t\t}\n\t\t\tif t == \"hysteria\" {\n\t\t\t\tproxy[\"auth-str\"] = obMap[\"auth_str\"]\n\t\t\t\tif obfs, ok := obMap[\"obfs\"].(string); ok {\n\t\t\t\t\tproxy[\"obfs\"] = obfs\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\t\t\tif obfs, ok := obMap[\"obfs\"].(map[string]interface{}); ok {\n\t\t\t\t\tproxy[\"obfs\"] = obfs[\"type\"]\n\t\t\t\t\tproxy[\"obfs-password\"] = obfs[\"password\"]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif portLists, ok := obMap[\"server_ports\"].([]interface{}); ok {\n\t\t\t\tvar ports []string\n\t\t\t\tfor _, portList := range portLists {\n\t\t\t\t\tportRange, _ := portList.(string)\n\t\t\t\t\tports = append(ports, strings.ReplaceAll(portRange, \":\", \"-\"))\n\t\t\t\t}\n\t\t\t\tproxy[\"ports\"] = strings.Join(ports, \",\")\n\t\t\t}\n\t\tcase \"anytls\":\n\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\t\tif tls, ok := obMap[\"tls\"].(map[string]interface{}); ok {\n\t\t\t\tproxy[\"sni\"] = tls[\"server_name\"]\n\t\t\t\tproxy[\"skip-cert-verify\"] = tls[\"insecure\"]\n\t\t\t}\n\t\tcase \"shadowsocks\":\n\t\t\tproxy[\"type\"] = \"ss\"\n\t\t\tproxy[\"cipher\"] = obMap[\"method\"]\n\t\t\tproxy[\"password\"] = obMap[\"password\"]\n\t\t\tif network, ok := obMap[\"network\"].(string); ok && network != \"tcp\" {\n\t\t\t\tproxy[\"udp\"] = true\n\t\t\t}\n\t\t\tif uot, ok := obMap[\"udp_over_tcp\"].(bool); ok && uot {\n\t\t\t\tproxy[\"udp-over-tcp\"] = true\n\t\t\t}\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\t// TLS params\n\t\ttls, isTls := obMap[\"tls\"].(map[string]interface{})\n\t\tif isTls {\n\t\t\ttlsEnabled, ok := tls[\"enabled\"].(bool)\n\t\t\tif ok && !tlsEnabled {\n\t\t\t\tisTls = false\n\t\t\t}\n\t\t}\n\t\tif isTls {\n\t\t\tproxy[\"tls\"] = tls[\"enabled\"]\n\n\t\t\t// ALPN if exists\n\t\t\tif alpn, ok := tls[\"alpn\"].([]interface{}); ok {\n\t\t\t\tproxy[\"alpn\"] = alpn\n\t\t\t}\n\n\t\t\t// Add reality if exists\n\t\t\tif reality, ok := tls[\"reality\"].(map[string]interface{}); ok && reality[\"enabled\"].(bool) {\n\t\t\t\treality_opts := make(map[string]interface{})\n\t\t\t\tif pbk, ok := reality[\"public_key\"].(string); ok {\n\t\t\t\t\treality_opts[\"public-key\"] = pbk\n\t\t\t\t}\n\t\t\t\tif sid, ok := reality[\"short_id\"].(string); ok {\n\t\t\t\t\treality_opts[\"short-id\"] = sid\n\t\t\t\t}\n\t\t\t\tproxy[\"reality-opts\"] = reality_opts\n\t\t\t}\n\t\t\tif utls, ok := tls[\"utls\"].(map[string]interface{}); ok {\n\t\t\t\tif enabled, ok := utls[\"enabled\"].(bool); ok && enabled {\n\t\t\t\t\tif fp, ok := utls[\"fingerprint\"].(string); ok {\n\t\t\t\t\t\tproxy[\"client-fingerprint\"] = fp\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif sni, ok := tls[\"server_name\"].(string); ok {\n\t\t\t\tif t == \"http\" {\n\t\t\t\t\tproxy[\"sni\"] = sni\n\t\t\t\t} else {\n\t\t\t\t\tproxy[\"servername\"] = sni\n\t\t\t\t}\n\t\t\t}\n\t\t\tif insecure, ok := tls[\"insecure\"].(bool); ok && insecure {\n\t\t\t\tproxy[\"skip-cert-verify\"] = insecure\n\t\t\t}\n\t\t\t// ech outbounds\n\t\t\tif ech, ok := tls[\"ech\"].(interface{}); ok {\n\t\t\t\tech_data, _ := ech.(map[string]interface{})\n\t\t\t\tech_config, _ := ech_data[\"config\"].([]interface{})\n\t\t\t\tech_string := \"\"\n\t\t\t\tfor i := 1; i < len(ech_config)-1; i++ {\n\t\t\t\t\tech_string += ech_config[i].(string)\n\t\t\t\t}\n\t\t\t\tproxy[\"ech-opts\"] = map[string]interface{}{\n\t\t\t\t\t\"enable\": true,\n\t\t\t\t\t\"config\": ech_string,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Transport if exist\n\t\tif transport, ok := obMap[\"transport\"].(map[string]interface{}); ok {\n\t\t\ttt, _ := transport[\"type\"].(string)\n\t\t\tswitch tt {\n\t\t\tcase \"http\":\n\t\t\t\thttpOpts := make(map[string]interface{})\n\t\t\t\tif path, ok := transport[\"path\"].([]interface{}); ok {\n\t\t\t\t\thttpOpts[\"path\"] = path[0]\n\t\t\t\t} else if path, ok := transport[\"path\"].(string); ok {\n\t\t\t\t\thttpOpts[\"path\"] = path\n\t\t\t\t}\n\t\t\t\tif host, ok := transport[\"host\"].([]interface{}); ok {\n\t\t\t\t\thttpOpts[\"host\"] = host[0]\n\t\t\t\t}\n\t\t\t\tif isTls {\n\t\t\t\t\tproxy[\"network\"] = \"h2\"\n\t\t\t\t\tproxy[\"h2-opts\"] = httpOpts\n\t\t\t\t} else {\n\t\t\t\t\tproxy[\"network\"] = \"http\"\n\t\t\t\t\tproxy[\"http-opts\"] = map[string]interface{}{\"path\": []interface{}{httpOpts[\"path\"]}, \"host\": httpOpts[\"host\"]}\n\t\t\t\t}\n\t\t\tcase \"ws\", \"httpupgrade\":\n\t\t\t\tproxy[\"network\"] = \"ws\"\n\t\t\t\twsOpts := make(map[string]interface{})\n\t\t\t\tif path, ok := transport[\"path\"].(string); ok {\n\t\t\t\t\twsOpts[\"path\"] = path\n\t\t\t\t}\n\t\t\t\tif headers, ok := transport[\"headers\"].([]interface{}); ok {\n\t\t\t\t\twsOpts[\"headers\"] = headers\n\t\t\t\t}\n\t\t\t\tif ed, ok := transport[\"early_data_header_name\"].(string); ok {\n\t\t\t\t\twsOpts[\"early-data-header-name\"] = ed\n\t\t\t\t}\n\t\t\t\tif tt == \"httpupgrade\" {\n\t\t\t\t\twsOpts[\"v2ray-http-upgrade\"] = true\n\t\t\t\t}\n\t\t\t\tproxy[\"ws-opts\"] = wsOpts\n\t\t\tcase \"grpc\":\n\t\t\t\tproxy[\"network\"] = \"grpc\"\n\t\t\t\tgrpcOpts := make(map[string]interface{})\n\t\t\t\tif service_name, ok := transport[\"service_name\"].(string); ok {\n\t\t\t\t\tgrpcOpts[\"grpc-service-name\"] = service_name\n\t\t\t\t}\n\t\t\t\tproxy[\"grpc-opts\"] = grpcOpts\n\t\t\t}\n\t\t}\n\n\t\t// Multiplex\n\t\tif mux, ok := obMap[\"multiplex\"].(map[string]interface{}); ok {\n\t\t\tif enabled, ok := mux[\"enabled\"].(bool); ok && enabled {\n\t\t\t\tsmux := make(map[string]interface{})\n\t\t\t\tsmux[\"enabled\"] = true\n\t\t\t\tif protocol, ok := mux[\"protocol\"].(string); ok {\n\t\t\t\t\tsmux[\"protocol\"] = protocol\n\t\t\t\t}\n\t\t\t\tif _, ok := mux[\"max_connections\"].(float64); ok {\n\t\t\t\t\tsmux[\"max-connections\"] = mux[\"max_connections\"]\n\t\t\t\t}\n\t\t\t\tif _, ok := mux[\"min_streams\"].(float64); ok {\n\t\t\t\t\tsmux[\"min-streams\"] = mux[\"min_streams\"]\n\t\t\t\t}\n\t\t\t\tif _, ok := mux[\"max_streams\"].(float64); ok {\n\t\t\t\t\tsmux[\"max-streams\"] = mux[\"max_streams\"]\n\t\t\t\t}\n\t\t\t\tif _, ok := mux[\"padding\"].(bool); ok {\n\t\t\t\t\tsmux[\"padding\"] = mux[\"padding\"]\n\t\t\t\t}\n\t\t\t\tif brutal, ok := mux[\"brutal\"].(map[string]interface{}); ok {\n\t\t\t\t\tif enabled, ok := brutal[\"enabled\"].(bool); ok && enabled {\n\t\t\t\t\t\tbrutalOpts := make(map[string]interface{})\n\t\t\t\t\t\tbrutalOpts[\"enabled\"] = true\n\t\t\t\t\t\tif _, ok := brutal[\"up_mbps\"].(float64); ok {\n\t\t\t\t\t\t\tbrutalOpts[\"up\"] = brutal[\"up_mbps\"]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif _, ok := brutal[\"down_mbps\"].(float64); ok {\n\t\t\t\t\t\t\tbrutalOpts[\"down\"] = brutal[\"down_mbps\"]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsmux[\"brutal-opts\"] = brutalOpts\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tproxy[\"smux\"] = smux\n\t\t\t}\n\t\t}\n\n\t\tproxies = append(proxies, proxy)\n\t\tproxyTags = append(proxyTags, obMap[\"tag\"].(string))\n\t}\n\n\tvar proxyGroups []map[string]interface{}\n\terr := yaml.Unmarshal([]byte(ProxyGroups), &proxyGroups)\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t}\n\n\tproxyGroups[1][\"proxies\"] = proxyTags\n\tproxyGroups[0][\"proxies\"] = append([]string{proxyGroups[1][\"name\"].(string)}, proxyTags...)\n\n\toutput := map[string]interface{}{\n\t\t\"proxies\":      proxies,\n\t\t\"proxy-groups\": proxyGroups,\n\t}\n\n\treturn yaml.Marshal(output)\n}\n"
  },
  {
    "path": "sub/jsonService.go",
    "content": "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-ui/database/model\"\n\t\"github.com/alireza0/s-ui/service\"\n\t\"github.com/alireza0/s-ui/util\"\n)\n\nconst defaultJson = `\n{\n  \"inbounds\": [\n    {\n      \"type\": \"tun\",\n      \"address\": [\n\t\t\t\t\"172.19.0.1/30\",\n\t\t\t\t\"fdfe:dcba:9876::1/126\"\n\t\t\t],\n      \"mtu\": 9000,\n      \"auto_route\": true,\n      \"strict_route\": false,\n      \"endpoint_independent_nat\": false,\n      \"stack\": \"system\",\n      \"platform\": {\n        \"http_proxy\": {\n          \"enabled\": true,\n          \"server\": \"127.0.0.1\",\n          \"server_port\": 2080\n        }\n      }\n    },\n    {\n      \"type\": \"mixed\",\n      \"listen\": \"127.0.0.1\",\n      \"listen_port\": 2080,\n      \"users\": []\n    }\n  ]\n}\n`\n\ntype JsonService struct {\n\tservice.SettingService\n\tLinkService\n}\n\nfunc (j *JsonService) GetJson(subId string, format string) (*string, []string, error) {\n\tvar jsonConfig map[string]interface{}\n\n\tclient, inDatas, err := j.getData(subId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\toutbounds, outTags, err := j.getOutbounds(client.Config, inDatas)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tlinks := j.LinkService.GetLinks(&client.Links, \"external\", \"\")\n\ttagNumEnable := 0\n\tif len(links) > 1 {\n\t\ttagNumEnable = 1\n\t}\n\tfor index, link := range links {\n\t\tjson, tag, err := util.GetOutbound(link, (index+1)*tagNumEnable)\n\t\tif err == nil && len(tag) > 0 {\n\t\t\t*outbounds = append(*outbounds, *json)\n\t\t\t*outTags = append(*outTags, tag)\n\t\t}\n\t}\n\n\tj.addDefaultOutbounds(outbounds, outTags)\n\n\terr = json.Unmarshal([]byte(defaultJson), &jsonConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjsonConfig[\"outbounds\"] = outbounds\n\n\t// Add other objects from settings\n\tj.addOthers(&jsonConfig)\n\n\tresult, _ := json.MarshalIndent(jsonConfig, \"\", \"  \")\n\tresultStr := string(result)\n\n\tupdateInterval, _ := j.SettingService.GetSubUpdates()\n\theaders := util.GetHeaders(client, updateInterval)\n\n\treturn &resultStr, headers, nil\n}\n\nfunc (j *JsonService) getData(subId string) (*model.Client, []*model.Inbound, error) {\n\tdb := database.GetDB()\n\tclient := &model.Client{}\n\terr := db.Model(model.Client{}).Where(\"enable = true and name = ?\", subId).First(client).Error\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar clientInbounds []uint\n\terr = json.Unmarshal(client.Inbounds, &clientInbounds)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar inbounds []*model.Inbound\n\terr = db.Model(model.Inbound{}).Preload(\"Tls\").Where(\"id in ?\", clientInbounds).Find(&inbounds).Error\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn client, inbounds, nil\n}\n\nfunc (j *JsonService) getOutbounds(clientConfig json.RawMessage, inbounds []*model.Inbound) (*[]map[string]interface{}, *[]string, error) {\n\tvar outbounds []map[string]interface{}\n\tvar configs map[string]interface{}\n\tvar outTags []string\n\n\terr := json.Unmarshal(clientConfig, &configs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor _, inData := range inbounds {\n\t\tif len(inData.OutJson) < 5 {\n\t\t\tcontinue\n\t\t}\n\t\tvar outbound map[string]interface{}\n\t\terr = json.Unmarshal(inData.OutJson, &outbound)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tprotocol, _ := outbound[\"type\"].(string)\n\n\t\t// Shadowsocks\n\t\tif protocol == \"shadowsocks\" {\n\t\t\tvar userPass []string\n\t\t\tvar inbOptions map[string]interface{}\n\t\t\terr = json.Unmarshal(inData.Options, &inbOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tmethod, _ := inbOptions[\"method\"].(string)\n\t\t\tif strings.HasPrefix(method, \"2022\") {\n\t\t\t\tinbPass, _ := inbOptions[\"password\"].(string)\n\t\t\t\tuserPass = append(userPass, inbPass)\n\t\t\t}\n\t\t\tvar pass string\n\t\t\tif method == \"2022-blake3-aes-128-gcm\" {\n\t\t\t\tpass, _ = configs[\"shadowsocks16\"].(map[string]interface{})[\"password\"].(string)\n\t\t\t} else {\n\t\t\t\tpass, _ = configs[\"shadowsocks\"].(map[string]interface{})[\"password\"].(string)\n\t\t\t}\n\t\t\tuserPass = append(userPass, pass)\n\t\t\toutbound[\"password\"] = strings.Join(userPass, \":\")\n\t\t} else { // Other protocols\n\t\t\tconfig, _ := configs[protocol].(map[string]interface{})\n\t\t\tfor key, value := range config {\n\t\t\t\tif key == \"name\" || key == \"alterId\" || (key == \"flow\" && inData.TlsId == 0) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\toutbound[key] = value\n\t\t\t}\n\t\t}\n\n\t\tvar addrs []map[string]interface{}\n\t\terr = json.Unmarshal(inData.Addrs, &addrs)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttag, _ := outbound[\"tag\"].(string)\n\t\tif len(addrs) == 0 {\n\t\t\t// For mixed protocol, use separated socks and http\n\t\t\tif protocol == \"mixed\" {\n\t\t\t\toutbound[\"tag\"] = tag\n\t\t\t\tj.pushMixed(&outbounds, &outTags, outbound)\n\t\t\t} else {\n\t\t\t\toutTags = append(outTags, tag)\n\t\t\t\toutbounds = append(outbounds, outbound)\n\t\t\t}\n\t\t} else {\n\t\t\tfor index, addr := range addrs {\n\t\t\t\t// Copy original config\n\t\t\t\tnewOut := make(map[string]interface{}, len(outbound))\n\t\t\t\tfor key, value := range outbound {\n\t\t\t\t\tnewOut[key] = value\n\t\t\t\t}\n\t\t\t\t// Change and push copied config\n\t\t\t\tnewOut[\"server\"], _ = addr[\"server\"].(string)\n\t\t\t\tport, _ := addr[\"server_port\"].(float64)\n\t\t\t\tnewOut[\"server_port\"] = int(port)\n\n\t\t\t\t// Override TLS\n\t\t\t\tif addrTls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\t\t\toutTls, _ := newOut[\"tls\"].(map[string]interface{})\n\t\t\t\t\tif outTls == nil {\n\t\t\t\t\t\toutTls = make(map[string]interface{})\n\t\t\t\t\t}\n\t\t\t\t\tfor key, value := range addrTls {\n\t\t\t\t\t\toutTls[key] = value\n\t\t\t\t\t}\n\t\t\t\t\tnewOut[\"tls\"] = outTls\n\t\t\t\t}\n\n\t\t\t\tremark, _ := addr[\"remark\"].(string)\n\t\t\t\tnewTag := fmt.Sprintf(\"%d.%s%s\", index+1, tag, remark)\n\t\t\t\tnewOut[\"tag\"] = newTag\n\t\t\t\t// For mixed protocol, use separated socks and http\n\t\t\t\tif protocol == \"mixed\" {\n\t\t\t\t\tj.pushMixed(&outbounds, &outTags, newOut)\n\t\t\t\t} else {\n\t\t\t\t\toutTags = append(outTags, newTag)\n\t\t\t\t\toutbounds = append(outbounds, newOut)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn &outbounds, &outTags, nil\n}\n\nfunc (j *JsonService) addDefaultOutbounds(outbounds *[]map[string]interface{}, outTags *[]string) {\n\toutbound := []map[string]interface{}{\n\t\t{\n\t\t\t\"outbounds\": append([]string{\"auto\", \"direct\"}, *outTags...),\n\t\t\t\"tag\":       \"proxy\",\n\t\t\t\"type\":      \"selector\",\n\t\t},\n\t\t{\n\t\t\t\"tag\":       \"auto\",\n\t\t\t\"type\":      \"urltest\",\n\t\t\t\"outbounds\": outTags,\n\t\t\t\"url\":       \"http://www.gstatic.com/generate_204\",\n\t\t\t\"interval\":  \"10m\",\n\t\t\t\"tolerance\": 50,\n\t\t},\n\t\t{\n\t\t\t\"type\": \"direct\",\n\t\t\t\"tag\":  \"direct\",\n\t\t},\n\t}\n\t*outbounds = append(outbound, *outbounds...)\n}\n\nfunc (j *JsonService) addOthers(jsonConfig *map[string]interface{}) error {\n\trules_start := []interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"action\": \"sniff\",\n\t\t},\n\t\tmap[string]interface{}{\n\t\t\t\"clash_mode\": \"Direct\",\n\t\t\t\"action\":     \"route\",\n\t\t\t\"outbound\":   \"direct\",\n\t\t},\n\t}\n\trules_end := []interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"clash_mode\": \"Global\",\n\t\t\t\"action\":     \"route\",\n\t\t\t\"outbound\":   \"proxy\",\n\t\t},\n\t}\n\troute := map[string]interface{}{\n\t\t\"auto_detect_interface\": true,\n\t\t\"final\":                 \"proxy\",\n\t\t\"rules\":                 rules_start,\n\t}\n\n\tothersStr, err := j.SettingService.GetSubJsonExt()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(othersStr) == 0 {\n\t\t(*jsonConfig)[\"route\"] = route\n\t\treturn nil\n\t}\n\tvar othersJson map[string]interface{}\n\terr = json.Unmarshal([]byte(othersStr), &othersJson)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, ok := othersJson[\"log\"]; ok {\n\t\t(*jsonConfig)[\"log\"] = othersJson[\"log\"]\n\t}\n\tif _, ok := othersJson[\"dns\"]; ok {\n\t\t(*jsonConfig)[\"dns\"] = othersJson[\"dns\"]\n\t}\n\tif _, ok := othersJson[\"inbounds\"]; ok {\n\t\t(*jsonConfig)[\"inbounds\"] = othersJson[\"inbounds\"]\n\t}\n\tif _, ok := othersJson[\"experimental\"]; ok {\n\t\t(*jsonConfig)[\"experimental\"] = othersJson[\"experimental\"]\n\t}\n\tif _, ok := othersJson[\"rule_set\"]; ok {\n\t\troute[\"rule_set\"] = othersJson[\"rule_set\"]\n\t}\n\tif settingRules, ok := othersJson[\"rules\"].([]interface{}); ok {\n\t\trules := append(rules_start, settingRules...)\n\t\troute[\"rules\"] = append(rules, rules_end...)\n\t}\n\tif defaultDomainResolver, ok := othersJson[\"default_domain_resolver\"].(string); ok {\n\t\troute[\"default_domain_resolver\"] = defaultDomainResolver\n\t}\n\t(*jsonConfig)[\"route\"] = route\n\n\treturn nil\n}\n\nfunc (j *JsonService) pushMixed(outbounds *[]map[string]interface{}, outTags *[]string, out map[string]interface{}) {\n\tsocksOut := make(map[string]interface{}, 1)\n\thttpOut := make(map[string]interface{}, 1)\n\tfor key, value := range out {\n\t\tsocksOut[key] = value\n\t\thttpOut[key] = value\n\t}\n\tsocksTag := fmt.Sprintf(\"%s-socks\", out[\"tag\"])\n\thttpTag := fmt.Sprintf(\"%s-http\", out[\"tag\"])\n\tsocksOut[\"type\"] = \"socks\"\n\thttpOut[\"type\"] = \"http\"\n\tsocksOut[\"tag\"] = socksTag\n\thttpOut[\"tag\"] = httpTag\n\t*outbounds = append(*outbounds, socksOut, httpOut)\n\t*outTags = append(*outTags, socksTag, httpTag)\n}\n"
  },
  {
    "path": "sub/linkService.go",
    "content": "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)\n\ntype Link struct {\n\tType   string `json:\"type\"`\n\tRemark string `json:\"remark\"`\n\tUri    string `json:\"uri\"`\n}\n\ntype LinkService struct {\n}\n\nfunc (s *LinkService) GetLinks(linkJson *json.RawMessage, types string, clientInfo string) []string {\n\tlinks := []Link{}\n\tvar result []string\n\terr := json.Unmarshal(*linkJson, &links)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tfor _, link := range links {\n\t\tswitch link.Type {\n\t\tcase \"external\":\n\t\t\tresult = append(result, link.Uri)\n\t\tcase \"sub\":\n\t\t\tsubLinks := util.GetExternalLink(link.Uri)\n\t\t\tresult = append(result, strings.Split(subLinks, \"\\n\")...)\n\t\tcase \"local\":\n\t\t\tif types == \"all\" {\n\t\t\t\tresult = append(result, s.addClientInfo(link.Uri, clientInfo))\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (s *LinkService) addClientInfo(uri string, clientInfo string) string {\n\tif len(clientInfo) == 0 {\n\t\treturn uri\n\t}\n\tprotocol := strings.Split(uri, \"://\")\n\tif len(protocol) < 2 {\n\t\treturn uri\n\t}\n\tswitch protocol[0] {\n\tcase \"vmess\":\n\t\tvar vmessJson map[string]interface{}\n\t\tconfig, err := util.B64StrToByte(protocol[1])\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"sub: Error decoding vmess content:\", err)\n\t\t\treturn uri\n\t\t}\n\t\terr = json.Unmarshal(config, &vmessJson)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"sub: Error decoding vmess content:\", err)\n\t\t\treturn uri\n\t\t}\n\t\tvmessJson[\"ps\"] = vmessJson[\"ps\"].(string) + clientInfo\n\t\tresult, err := json.MarshalIndent(vmessJson, \"\", \"  \")\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"sub: Error decoding vmess + clientInfo content:\", err)\n\t\t\treturn uri\n\t\t}\n\t\treturn \"vmess://\" + util.ByteToB64Str(result)\n\tdefault:\n\t\treturn uri + clientInfo\n\t}\n}\n"
  },
  {
    "path": "sub/sub.go",
    "content": "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\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/middleware\"\n\t\"github.com/alireza0/s-ui/network\"\n\t\"github.com/alireza0/s-ui/service\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Server struct {\n\thttpServer *http.Server\n\tlistener   net.Listener\n\tctx        context.Context\n\tcancel     context.CancelFunc\n\n\tservice.SettingService\n}\n\nfunc NewServer() *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n}\n\nfunc (s *Server) initRouter() (*gin.Engine, error) {\n\tif config.IsDebug() {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.DefaultWriter = io.Discard\n\t\tgin.DefaultErrorWriter = io.Discard\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\tengine := gin.Default()\n\n\tsubPath, err := s.SettingService.GetSubPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubDomain, err := s.SettingService.GetSubDomain()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif subDomain != \"\" {\n\t\tengine.Use(middleware.DomainValidator(subDomain))\n\t}\n\n\tg := engine.Group(subPath)\n\tNewSubHandler(g)\n\n\treturn engine, nil\n}\n\nfunc (s *Server) Start() (err error) {\n\t//This is an anonymous function, no function name\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ts.Stop()\n\t\t}\n\t}()\n\n\tengine, err := s.initRouter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcertFile, err := s.SettingService.GetSubCertFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tkeyFile, err := s.SettingService.GetSubKeyFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlisten, err := s.SettingService.GetSubListen()\n\tif err != nil {\n\t\treturn err\n\t}\n\tport, err := s.SettingService.GetSubPort()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlistenAddr := net.JoinHostPort(listen, strconv.Itoa(port))\n\tlistener, err := net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif certFile != \"\" || keyFile != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\treturn err\n\t\t}\n\t\tc := &tls.Config{\n\t\t\tCertificates: []tls.Certificate{cert},\n\t\t}\n\t\tlistener = network.NewAutoHttpsListener(listener)\n\t\tlistener = tls.NewListener(listener, c)\n\t}\n\n\tif certFile != \"\" || keyFile != \"\" {\n\t\tlogger.Info(\"Sub server run https on\", listener.Addr())\n\t} else {\n\t\tlogger.Info(\"Sub server run http on\", listener.Addr())\n\t}\n\ts.listener = listener\n\n\ts.httpServer = &http.Server{\n\t\tHandler: engine,\n\t}\n\n\tgo func() {\n\t\ts.httpServer.Serve(listener)\n\t}()\n\n\treturn nil\n}\n\nfunc (s *Server) Stop() error {\n\ts.cancel()\n\tvar err error\n\tif s.httpServer != nil {\n\t\terr = s.httpServer.Shutdown(s.ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif s.listener != nil {\n\t\terr = s.listener.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Server) GetCtx() context.Context {\n\treturn s.ctx\n}\n"
  },
  {
    "path": "sub/subHandler.go",
    "content": "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\"\n)\n\ntype SubHandler struct {\n\tservice.SettingService\n\tSubService\n\tJsonService\n\tClashService\n}\n\nfunc NewSubHandler(g *gin.RouterGroup) {\n\ta := &SubHandler{}\n\ta.initRouter(g)\n}\n\nfunc (s *SubHandler) initRouter(g *gin.RouterGroup) {\n\tg.GET(\"/:subid\", s.subs)\n\tg.HEAD(\"/:subid\", s.subHeaders)\n}\n\nfunc (s *SubHandler) subs(c *gin.Context) {\n\tvar headers []string\n\tvar result *string\n\tvar err error\n\tsubId := c.Param(\"subid\")\n\tformat, isFormat := c.GetQuery(\"format\")\n\tif isFormat {\n\t\tswitch format {\n\t\tcase \"json\":\n\t\t\tresult, headers, err = s.JsonService.GetJson(subId, format)\n\t\tcase \"clash\":\n\t\t\tresult, headers, err = s.ClashService.GetClash(subId)\n\t\t}\n\t\tif err != nil || result == nil {\n\t\t\tlogger.Error(err)\n\t\t\tc.String(400, \"Error!\")\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tresult, headers, err = s.SubService.GetSubs(subId)\n\t\tif err != nil || result == nil {\n\t\t\tlogger.Error(err)\n\t\t\tc.String(400, \"Error!\")\n\t\t\treturn\n\t\t}\n\t}\n\n\ts.addHeaders(c, headers)\n\n\tc.String(200, *result)\n}\n\nfunc (s *SubHandler) subHeaders(c *gin.Context) {\n\tsubId := c.Param(\"subid\")\n\tclient, err := s.SubService.getClientBySubId(subId)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\tc.String(400, \"Error!\")\n\t\treturn\n\t}\n\n\theaders := s.SubService.getClientHeaders(client)\n\ts.addHeaders(c, headers)\n\n\tc.Status(200)\n}\n\nfunc (s *SubHandler) addHeaders(c *gin.Context, headers []string) {\n\tc.Writer.Header().Set(\"Subscription-Userinfo\", headers[0])\n\tc.Writer.Header().Set(\"Profile-Update-Interval\", headers[1])\n\tc.Writer.Header().Set(\"Profile-Title\", headers[2])\n}\n"
  },
  {
    "path": "sub/subService.go",
    "content": "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/alireza0/s-ui/database/model\"\n\t\"github.com/alireza0/s-ui/service\"\n\t\"github.com/alireza0/s-ui/util\"\n)\n\ntype SubService struct {\n\tservice.SettingService\n\tLinkService\n}\n\nfunc (s *SubService) GetSubs(subId string) (*string, []string, error) {\n\tvar err error\n\n\tclient, err := s.getClientBySubId(subId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclientInfo := \"\"\n\tsubShowInfo, _ := s.SettingService.GetSubShowInfo()\n\tif subShowInfo {\n\t\tclientInfo = s.getClientInfo(client)\n\t}\n\n\tlinksArray := s.LinkService.GetLinks(&client.Links, \"all\", clientInfo)\n\tresult := strings.Join(linksArray, \"\\n\")\n\n\theaders := s.getClientHeaders(client)\n\n\tsubEncode, _ := s.SettingService.GetSubEncode()\n\tif subEncode {\n\t\tresult = base64.StdEncoding.EncodeToString([]byte(result))\n\t}\n\n\treturn &result, headers, nil\n}\n\nfunc (j *SubService) getClientBySubId(subId string) (*model.Client, error) {\n\tdb := database.GetDB()\n\tclient := &model.Client{}\n\terr := db.Model(model.Client{}).Where(\"enable = true and name = ?\", subId).First(client).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}\n\nfunc (s *SubService) getClientHeaders(client *model.Client) []string {\n\tupdateInterval, _ := s.SettingService.GetSubUpdates()\n\treturn util.GetHeaders(client, updateInterval)\n}\n\nfunc (s *SubService) getClientInfo(c *model.Client) string {\n\tnow := time.Now().Unix()\n\n\tvar result []string\n\tif vol := c.Volume - (c.Up + c.Down); vol > 0 {\n\t\tresult = append(result, fmt.Sprintf(\"%s%s\", s.formatTraffic(vol), \"📊\"))\n\t}\n\tif c.Expiry > 0 {\n\t\tresult = append(result, fmt.Sprintf(\"%d%s⏳\", (c.Expiry-now)/86400, \"Days\"))\n\t}\n\tif len(result) > 0 {\n\t\treturn \" \" + strings.Join(result, \" \")\n\t} else {\n\t\treturn \" ♾\"\n\t}\n}\n\nfunc (s *SubService) formatTraffic(trafficBytes int64) string {\n\tif trafficBytes < 1024 {\n\t\treturn fmt.Sprintf(\"%.2fB\", float64(trafficBytes)/float64(1))\n\t} else if trafficBytes < (1024 * 1024) {\n\t\treturn fmt.Sprintf(\"%.2fKB\", float64(trafficBytes)/float64(1024))\n\t} else if trafficBytes < (1024 * 1024 * 1024) {\n\t\treturn fmt.Sprintf(\"%.2fMB\", float64(trafficBytes)/float64(1024*1024))\n\t} else if trafficBytes < (1024 * 1024 * 1024 * 1024) {\n\t\treturn fmt.Sprintf(\"%.2fGB\", float64(trafficBytes)/float64(1024*1024*1024))\n\t} else if trafficBytes < (1024 * 1024 * 1024 * 1024 * 1024) {\n\t\treturn fmt.Sprintf(\"%.2fTB\", float64(trafficBytes)/float64(1024*1024*1024*1024))\n\t} else {\n\t\treturn fmt.Sprintf(\"%.2fEB\", float64(trafficBytes)/float64(1024*1024*1024*1024*1024))\n\t}\n}\n"
  },
  {
    "path": "util/base64.go",
    "content": "package util\n\nimport \"encoding/base64\"\n\n// Function to return decoded bytes if a string is Base64 encoded\nfunc StrOrBase64Encoded(str string) string {\n\tdecoded, err := base64.StdEncoding.DecodeString(str)\n\tif err == nil {\n\t\treturn string(decoded)\n\t}\n\treturn str\n}\n\nfunc B64StrToByte(str string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(str)\n}\n\nfunc ByteToB64Str(b []byte) string {\n\treturn base64.StdEncoding.EncodeToString(b)\n}\n"
  },
  {
    "path": "util/common/array.go",
    "content": "package common\n\n// UnionUintArray returns a new unique slice that contains all elements from both input slices\nfunc UnionUintArray(a []uint, b []uint) []uint {\n\tm := make(map[uint]bool)\n\tfor _, v := range a {\n\t\tm[v] = true\n\t}\n\tfor _, v := range b {\n\t\tm[v] = true\n\t}\n\tvar res []uint\n\tfor k := range m {\n\t\tres = append(res, k)\n\t}\n\treturn res\n}\n\n// Find different elements in two slices\n// Returns elements in 'a' that are not in 'b' and elements in 'b' that are not in 'a'\nfunc DiffUintArray(a []uint, b []uint) []uint {\n\tdifferent := []uint{}\n\tset := make(map[uint]bool)\n\n\tfor _, item := range a {\n\t\tset[item] = true\n\t}\n\tfor _, item := range b {\n\t\tif !set[item] {\n\t\t\tdifferent = append(different, item)\n\t\t}\n\t}\n\n\tset = make(map[uint]bool)\n\tfor _, item := range b {\n\t\tset[item] = true\n\t}\n\tfor _, item := range a {\n\t\tif !set[item] {\n\t\t\tdifferent = append(different, item)\n\t\t}\n\t}\n\n\treturn different\n}\n"
  },
  {
    "path": "util/common/err.go",
    "content": "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 ...interface{}) error {\n\tmsg := fmt.Sprintf(format, a...)\n\treturn errors.New(msg)\n}\n\nfunc NewError(a ...interface{}) error {\n\tmsg := fmt.Sprintln(a...)\n\treturn errors.New(msg)\n}\n\nfunc Recover(msg string) interface{} {\n\tpanicErr := recover()\n\tif panicErr != nil {\n\t\tif msg != \"\" {\n\t\t\tlogger.Error(msg, \"panic:\", panicErr)\n\t\t}\n\t}\n\treturn panicErr\n}\n"
  },
  {
    "path": "util/common/random.go",
    "content": "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 = []rune{\n\t\t'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n\t}\n\n\tfallbackRand = mrand.New(mrand.NewSource(time.Now().UnixNano()))\n\tfallbackMu   = sync.Mutex{}\n)\n\nfunc Random(n int) string {\n\tif n <= 0 || len(allSeq) == 0 {\n\t\treturn \"\"\n\t}\n\tresult := make([]rune, n)\n\tmaxBig := big.NewInt(int64(len(allSeq)))\n\tfor i := 0; i < n; i++ {\n\t\tnum, err := crand.Int(crand.Reader, maxBig)\n\t\tif err != nil {\n\t\t\t// fallback\n\t\t\tfallbackMu.Lock()\n\t\t\tresult[i] = allSeq[fallbackRand.Intn(len(allSeq))]\n\t\t\tfallbackMu.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\tresult[i] = allSeq[int(num.Int64())]\n\t}\n\treturn string(result)\n}\n\nfunc RandomInt(n int) int {\n\tif n <= 0 {\n\t\treturn 0\n\t}\n\tmax := big.NewInt(int64(n))\n\tresult, err := crand.Int(crand.Reader, max)\n\tif err != nil {\n\t\t// fallback\n\t\tfallbackMu.Lock()\n\t\tdefer fallbackMu.Unlock()\n\t\treturn fallbackRand.Intn(n)\n\t}\n\treturn int(result.Int64())\n}\n"
  },
  {
    "path": "util/genLink.go",
    "content": "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/database/model\"\n\t\"github.com/alireza0/s-ui/util/common\"\n)\n\nvar InboundTypeWithLink = []string{\"socks\", \"http\", \"mixed\", \"shadowsocks\", \"naive\", \"hysteria\", \"hysteria2\", \"anytls\", \"tuic\", \"vless\", \"trojan\", \"vmess\"}\n\ntype LinkParam struct {\n\tKey   string\n\tValue string\n}\n\nfunc LinkGenerator(clientConfig json.RawMessage, i *model.Inbound, hostname string) []string {\n\tinbound, err := i.MarshalFull()\n\tif err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar tls map[string]interface{}\n\tif i.TlsId > 0 {\n\t\ttls = prepareTls(i.Tls)\n\t}\n\n\tvar userConfig map[string]map[string]interface{}\n\tif err := json.Unmarshal(clientConfig, &userConfig); err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar Addrs []map[string]interface{}\n\tif err := json.Unmarshal(i.Addrs, &Addrs); err != nil {\n\t\treturn []string{}\n\t}\n\tif len(Addrs) == 0 {\n\t\tAddrs = append(Addrs, map[string]interface{}{\n\t\t\t\"server\":      hostname,\n\t\t\t\"server_port\": (*inbound)[\"listen_port\"],\n\t\t\t\"remark\":      i.Tag,\n\t\t})\n\t\tif i.TlsId > 0 {\n\t\t\tAddrs[0][\"tls\"] = tls\n\t\t}\n\t} else {\n\t\tfor index, addr := range Addrs {\n\t\t\taddrRemark, _ := addr[\"remark\"].(string)\n\t\t\tAddrs[index][\"remark\"] = i.Tag + addrRemark\n\t\t\tif i.TlsId > 0 {\n\t\t\t\tnewTls := map[string]interface{}{}\n\t\t\t\tfor k, v := range tls {\n\t\t\t\t\tnewTls[k] = v\n\t\t\t\t}\n\n\t\t\t\t// Override tls\n\t\t\t\tif addrTls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\t\t\tfor k, v := range addrTls {\n\t\t\t\t\t\tnewTls[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tAddrs[index][\"tls\"] = newTls\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch i.Type {\n\tcase \"socks\":\n\t\treturn socksLink(userConfig[\"socks\"], Addrs)\n\tcase \"http\":\n\t\treturn httpLink(userConfig[\"http\"], Addrs)\n\tcase \"mixed\":\n\t\treturn append(\n\t\t\tsocksLink(userConfig[\"socks\"], Addrs),\n\t\t\thttpLink(userConfig[\"http\"], Addrs)...,\n\t\t)\n\tcase \"shadowsocks\":\n\t\treturn shadowsocksLink(userConfig, *inbound, Addrs)\n\tcase \"naive\":\n\t\treturn naiveLink(userConfig[\"naive\"], *inbound, Addrs)\n\tcase \"hysteria\":\n\t\treturn hysteriaLink(userConfig[\"hysteria\"], *inbound, Addrs)\n\tcase \"hysteria2\":\n\t\treturn hysteria2Link(userConfig[\"hysteria2\"], *inbound, Addrs)\n\tcase \"tuic\":\n\t\treturn tuicLink(userConfig[\"tuic\"], *inbound, Addrs)\n\tcase \"vless\":\n\t\treturn vlessLink(userConfig[\"vless\"], *inbound, Addrs)\n\tcase \"anytls\":\n\t\treturn anytlsLink(userConfig[\"anytls\"], Addrs)\n\tcase \"trojan\":\n\t\treturn trojanLink(userConfig[\"trojan\"], *inbound, Addrs)\n\tcase \"vmess\":\n\t\treturn vmessLink(userConfig[\"vmess\"], *inbound, Addrs)\n\t}\n\n\treturn []string{}\n}\n\nfunc prepareTls(t *model.Tls) map[string]interface{} {\n\tvar iTls, oTls map[string]interface{}\n\tif err := json.Unmarshal(t.Client, &oTls); err != nil {\n\t\treturn nil\n\t}\n\tif err := json.Unmarshal(t.Server, &iTls); err != nil {\n\t\treturn nil\n\t}\n\n\tfor k, v := range iTls {\n\t\tswitch k {\n\t\tcase \"enabled\", \"server_name\", \"alpn\":\n\t\t\toTls[k] = v\n\t\tcase \"reality\":\n\t\t\treality := v.(map[string]interface{})\n\t\t\tclientReality := oTls[\"reality\"].(map[string]interface{})\n\t\t\tclientReality[\"enabled\"] = reality[\"enabled\"]\n\t\t\tif shortIDs, hasSIds := reality[\"short_id\"].([]interface{}); hasSIds && len(shortIDs) > 0 {\n\t\t\t\tclientReality[\"short_id\"] = shortIDs[common.RandomInt(len(shortIDs))]\n\t\t\t}\n\t\t\toTls[\"reality\"] = clientReality\n\t\t}\n\t}\n\treturn oTls\n}\n\nfunc socksLink(userConfig map[string]interface{}, addrs []map[string]interface{}) []string {\n\tvar links []string\n\tfor _, addr := range addrs {\n\t\tlinks = append(links, fmt.Sprintf(\"socks5://%s:%s@%s:%d\", userConfig[\"username\"], userConfig[\"password\"], addr[\"server\"].(string), uint(addr[\"server_port\"].(float64))))\n\t}\n\treturn links\n}\n\nfunc httpLink(userConfig map[string]interface{}, addrs []map[string]interface{}) []string {\n\tvar links []string\n\tprotocol := \"http\"\n\tfor _, addr := range addrs {\n\t\tif addr[\"tls\"] != nil {\n\t\t\tprotocol = \"https\"\n\t\t}\n\t\tlinks = append(links, fmt.Sprintf(\"%s://%s:%s@%s:%d\", protocol, userConfig[\"username\"], userConfig[\"password\"], addr[\"server\"].(string), uint(addr[\"server_port\"].(float64))))\n\t}\n\treturn links\n}\n\nfunc shadowsocksLink(\n\tuserConfig map[string]map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tvar userPass []string\n\tmethod, _ := inbound[\"method\"].(string)\n\tif strings.HasPrefix(method, \"2022\") {\n\t\tinbPass, _ := inbound[\"password\"].(string)\n\t\tuserPass = append(userPass, inbPass)\n\t}\n\tvar pass string\n\tif method == \"2022-blake3-aes-128-gcm\" {\n\t\tpass, _ = userConfig[\"shadowsocks16\"][\"password\"].(string)\n\t} else {\n\t\tpass, _ = userConfig[\"shadowsocks\"][\"password\"].(string)\n\t}\n\tuserPass = append(userPass, pass)\n\n\turiBase := fmt.Sprintf(\"ss://%s\", toBase64([]byte(fmt.Sprintf(\"%s:%s\", method, strings.Join(userPass, \":\")))))\n\n\tvar links []string\n\tfor _, addr := range addrs {\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\tlinks = append(links, fmt.Sprintf(\"%s@%s:%.0f#%s\", uriBase, addr[\"server\"].(string), port, addr[\"remark\"].(string)))\n\t}\n\treturn links\n}\n\nfunc naiveLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tpassword, _ := userConfig[\"password\"].(string)\n\tusername, _ := userConfig[\"username\"].(string)\n\n\tbaseUri := \"http2://\"\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tvar params []LinkParam\n\t\tparams = append(params, LinkParam{\"padding\", \"1\"})\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\tif sni, ok := tls[\"server_name\"].(string); ok {\n\t\t\t\tparams = append(params, LinkParam{\"peer\", sni})\n\t\t\t}\n\t\t\tif alpn, ok := tls[\"alpn\"].([]interface{}); ok {\n\t\t\t\talpnList := make([]string, len(alpn))\n\t\t\t\tfor i, v := range alpn {\n\t\t\t\t\talpnList[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tparams = append(params, LinkParam{\"alpn\", strings.Join(alpnList, \",\")})\n\t\t\t}\n\t\t\tif insecure, ok := tls[\"insecure\"].(bool); ok && insecure {\n\t\t\t\tparams = append(params, LinkParam{\"insecure\", \"1\"})\n\t\t\t}\n\t\t}\n\t\tif tfo, ok := inbound[\"tcp_fast_open\"].(bool); ok && tfo {\n\t\t\tparams = append(params, LinkParam{\"tfo\", \"1\"})\n\t\t} else {\n\t\t\tparams = append(params, LinkParam{\"tfo\", \"0\"})\n\t\t}\n\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := baseUri + toBase64([]byte(fmt.Sprintf(\"%s:%s@%s:%.0f\", username, password, addr[\"server\"].(string), port)))\n\t\tlinks = append(links, addParams(uri, params, addr[\"remark\"].(string)))\n\t}\n\treturn links\n}\n\nfunc hysteriaLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tbaseUri := \"hysteria://\"\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tvar params []LinkParam\n\t\tif upmbps, ok := inbound[\"up_mbps\"].(float64); ok {\n\t\t\tparams = append(params, LinkParam{\"downmbps\", fmt.Sprintf(\"%.0f\", upmbps)})\n\t\t}\n\t\tif downmbps, ok := inbound[\"down_mbps\"].(float64); ok {\n\t\t\tparams = append(params, LinkParam{\"upmbps\", fmt.Sprintf(\"%.0f\", downmbps)})\n\t\t}\n\t\tif auth, ok := userConfig[\"auth_str\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"auth\", auth})\n\t\t}\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\tgetTlsParams(&params, tls, \"insecure\")\n\t\t}\n\t\tif obfs, ok := inbound[\"obfs\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"obfs\", obfs})\n\t\t}\n\t\tif tfo, ok := inbound[\"tcp_fast_open\"].(bool); ok && tfo {\n\t\t\tparams = append(params, LinkParam{\"fastopen\", \"1\"})\n\t\t} else {\n\t\t\tparams = append(params, LinkParam{\"fastopen\", \"0\"})\n\t\t}\n\t\tvar outJson map[string]interface{}\n\t\tif err := json.Unmarshal(inbound[\"out_json\"].(json.RawMessage), &outJson); err != nil {\n\t\t\treturn []string{} // Handle error\n\t\t}\n\t\tif mport, ok := outJson[\"server_ports\"].([]interface{}); ok {\n\t\t\tmportList := make([]string, len(mport))\n\t\t\tfor i, v := range mport {\n\t\t\t\tmportList[i] = v.(string)\n\t\t\t}\n\t\t\tparams = append(params, LinkParam{\"mport\", strings.Join(mportList, \",\")})\n\t\t}\n\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"%s%s:%.0f\", baseUri, addr[\"server\"].(string), port)\n\t\tlinks = append(links, addParams(uri, params, addr[\"remark\"].(string)))\n\t}\n\n\treturn links\n}\n\nfunc hysteria2Link(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tpassword, _ := userConfig[\"password\"].(string)\n\tbaseUri := fmt.Sprintf(\"%s%s@\", \"hysteria2://\", password)\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tvar params []LinkParam\n\t\tif upmbps, ok := inbound[\"up_mbps\"].(float64); ok {\n\t\t\tparams = append(params, LinkParam{\"downmbps\", fmt.Sprintf(\"%.0f\", upmbps)})\n\t\t}\n\t\tif downmbps, ok := inbound[\"down_mbps\"].(float64); ok {\n\t\t\tparams = append(params, LinkParam{\"upmbps\", fmt.Sprintf(\"%.0f\", downmbps)})\n\t\t}\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\tgetTlsParams(&params, tls, \"insecure\")\n\t\t}\n\t\tif obfs, ok := inbound[\"obfs\"].(map[string]interface{}); ok {\n\t\t\tif obfsType, ok := obfs[\"type\"].(string); ok {\n\t\t\t\tparams = append(params, LinkParam{\"obfs\", obfsType})\n\t\t\t}\n\t\t\tif obfsPassword, ok := obfs[\"password\"].(string); ok {\n\t\t\t\tparams = append(params, LinkParam{\"obfs-password\", obfsPassword})\n\t\t\t}\n\t\t}\n\t\tif tfo, ok := inbound[\"tcp_fast_open\"].(bool); ok && tfo {\n\t\t\tparams = append(params, LinkParam{\"fastopen\", \"1\"})\n\t\t} else {\n\t\t\tparams = append(params, LinkParam{\"fastopen\", \"0\"})\n\t\t}\n\t\tvar outJson map[string]interface{}\n\t\tif err := json.Unmarshal(inbound[\"out_json\"].(json.RawMessage), &outJson); err != nil {\n\t\t\treturn []string{} // Handle error\n\t\t}\n\t\tif mport, ok := outJson[\"server_ports\"].([]interface{}); ok {\n\t\t\tmportList := make([]string, len(mport))\n\t\t\tfor i, v := range mport {\n\t\t\t\tmportList[i] = v.(string)\n\t\t\t}\n\t\t\tparams = append(params, LinkParam{\"mport\", strings.Join(mportList, \",\")})\n\t\t}\n\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"%s%s:%.0f\", baseUri, addr[\"server\"].(string), port)\n\t\tlinks = append(links, addParams(uri, params, addr[\"remark\"].(string)))\n\t}\n\n\treturn links\n}\n\nfunc anytlsLink(\n\tuserConfig map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tpassword, _ := userConfig[\"password\"].(string)\n\tbaseUri := fmt.Sprintf(\"%s%s@\", \"anytls://\", password)\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tvar params []LinkParam\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\tgetTlsParams(&params, tls, \"insecure\")\n\t\t}\n\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"%s%s:%.0f\", baseUri, addr[\"server\"].(string), port)\n\t\tlinks = append(links, addParams(uri, params, addr[\"remark\"].(string)))\n\t}\n\n\treturn links\n}\n\nfunc tuicLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tpassword, _ := userConfig[\"password\"].(string)\n\tuuid, _ := userConfig[\"uuid\"].(string)\n\tbaseUri := fmt.Sprintf(\"%s%s:%s@\", \"tuic://\", uuid, password)\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tvar params []LinkParam\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok {\n\t\t\tgetTlsParams(&params, tls, \"insecure\")\n\t\t}\n\t\tif congestionControl, ok := inbound[\"congestion_control\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"congestion_control\", congestionControl})\n\t\t}\n\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"%s%s:%.0f\", baseUri, addr[\"server\"].(string), port)\n\t\tlinks = append(links, addParams(uri, params, addr[\"remark\"].(string)))\n\t}\n\n\treturn links\n}\n\nfunc vlessLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tuuid, _ := userConfig[\"uuid\"].(string)\n\tbaseParams := getTransportParams(inbound[\"transport\"])\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tparams := make([]LinkParam, len(baseParams))\n\t\tcopy(params, baseParams)\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok && tls[\"enabled\"].(bool) {\n\t\t\tgetTlsParams(&params, tls, \"allowInsecure\")\n\t\t\tif flow, ok := userConfig[\"flow\"].(string); ok {\n\t\t\t\tparams = append(params, LinkParam{\"flow\", flow})\n\t\t\t}\n\t\t}\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"vless://%s@%s:%.0f\", uuid, addr[\"server\"].(string), port)\n\t\turi = addParams(uri, params, addr[\"remark\"].(string))\n\t\tlinks = append(links, uri)\n\t}\n\n\treturn links\n}\n\nfunc trojanLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\tpassword, _ := userConfig[\"password\"].(string)\n\tbaseParams := getTransportParams(inbound[\"transport\"])\n\tvar links []string\n\n\tfor _, addr := range addrs {\n\t\tparams := make([]LinkParam, len(baseParams))\n\t\tcopy(params, baseParams)\n\t\tif tls, ok := addr[\"tls\"].(map[string]interface{}); ok && tls[\"enabled\"].(bool) {\n\t\t\tgetTlsParams(&params, tls, \"allowInsecure\")\n\t\t}\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\turi := fmt.Sprintf(\"trojan://%s@%s:%.0f\", password, addr[\"server\"].(string), port)\n\t\turi = addParams(uri, params, addr[\"remark\"].(string))\n\t\tlinks = append(links, uri)\n\t}\n\n\treturn links\n}\n\nfunc vmessLink(\n\tuserConfig map[string]interface{},\n\tinbound map[string]interface{},\n\taddrs []map[string]interface{}) []string {\n\n\tuuid, _ := userConfig[\"uuid\"].(string)\n\ttransportParams := getTransportParams(inbound[\"transport\"])\n\tvar links []string\n\n\tbaseParams := map[string]interface{}{\n\t\t\"v\":   \"2\",\n\t\t\"id\":  uuid,\n\t\t\"aid\": 0,\n\t}\n\n\tvar net, typ, host, path string\n\tfor _, p := range transportParams {\n\t\tswitch p.Key {\n\t\tcase \"type\":\n\t\t\tnet = p.Value\n\t\tcase \"host\":\n\t\t\thost = p.Value\n\t\tcase \"path\":\n\t\t\tpath = p.Value\n\t\t}\n\t}\n\n\tif net == \"http\" || net == \"tcp\" {\n\t\tbaseParams[\"net\"] = \"tcp\"\n\t\tif net == \"http\" {\n\t\t\ttyp = \"http\"\n\t\t}\n\t} else {\n\t\tbaseParams[\"net\"] = net\n\t}\n\n\tfor _, addr := range addrs {\n\t\tobj := make(map[string]interface{})\n\t\tfor k, v := range baseParams {\n\t\t\tobj[k] = v\n\t\t}\n\n\t\tobj[\"add\"], _ = addr[\"server\"].(string)\n\t\tport, _ := addr[\"server_port\"].(float64)\n\t\tobj[\"port\"] = fmt.Sprintf(\"%.0f\", port)\n\t\tobj[\"ps\"], _ = addr[\"remark\"].(string)\n\t\tif typ != \"\" {\n\t\t\tobj[\"type\"] = typ\n\t\t}\n\t\tif host != \"\" {\n\t\t\tobj[\"host\"] = host\n\t\t}\n\t\tif path != \"\" {\n\t\t\tobj[\"path\"] = path\n\t\t}\n\t\tpopulateVmessTlsParams(obj, addr[\"tls\"])\n\n\t\tjsonStr, _ := json.Marshal(obj)\n\n\t\turi := fmt.Sprintf(\"vmess://%s\", toBase64(jsonStr))\n\t\tlinks = append(links, uri)\n\t}\n\treturn links\n}\n\nfunc populateVmessTlsParams(obj map[string]interface{}, tlsConfig interface{}) {\n\tif tlsMap, ok := tlsConfig.(map[string]interface{}); ok && tlsMap[\"enabled\"].(bool) {\n\t\tobj[\"tls\"] = \"tls\"\n\t\tvar tlsParams []LinkParam\n\t\tgetTlsParams(&tlsParams, tlsMap, \"allowInsecure\")\n\t\tfor _, p := range tlsParams {\n\t\t\tswitch p.Key {\n\t\t\tcase \"security\":\n\t\t\t\t// ignore, as \"tls\" is already set\n\t\t\tcase \"allowInsecure\":\n\t\t\t\tobj[\"allowInsecure\"] = 1\n\t\t\tcase \"sni\":\n\t\t\t\tobj[\"sni\"] = p.Value\n\t\t\tcase \"fp\":\n\t\t\t\tobj[\"fp\"] = p.Value\n\t\t\tcase \"alpn\":\n\t\t\t\tobj[\"alpn\"] = p.Value\n\t\t\t}\n\t\t}\n\t} else {\n\t\tobj[\"tls\"] = \"none\"\n\t}\n}\n\nfunc toBase64(d []byte) string {\n\treturn base64.StdEncoding.EncodeToString(d)\n}\n\nfunc addParams(uri string, params []LinkParam, remark string) string {\n\tURL, _ := url.Parse(uri)\n\tvar q []string\n\tfor _, p := range params {\n\t\tswitch p.Key {\n\t\tcase \"mport\", \"alpn\":\n\t\t\tq = append(q, fmt.Sprintf(\"%s=%s\", p.Key, p.Value))\n\t\tdefault:\n\t\t\tq = append(q, fmt.Sprintf(\"%s=%s\", p.Key, url.QueryEscape(p.Value)))\n\t\t}\n\t}\n\tURL.RawQuery = strings.Join(q, \"&\")\n\tURL.Fragment = remark\n\treturn URL.String()\n}\n\nfunc getTransportParams(t interface{}) []LinkParam {\n\tvar params []LinkParam\n\ttrasport, _ := t.(map[string]interface{})\n\tvar transportType string\n\tif tt, ok := trasport[\"type\"].(string); ok {\n\t\ttransportType = tt\n\t} else {\n\t\ttransportType = \"tcp\"\n\t}\n\tparams = append(params, LinkParam{\"type\", transportType})\n\tif transportType == \"tcp\" {\n\t\treturn params\n\t}\n\n\tswitch transportType {\n\tcase \"http\":\n\t\tif host, ok := trasport[\"host\"].([]interface{}); ok {\n\t\t\tvar hosts []string\n\t\t\tfor _, v := range host {\n\t\t\t\thosts = append(hosts, v.(string))\n\t\t\t}\n\t\t\tparams = append(params, LinkParam{\"host\", strings.Join(hosts, \",\")})\n\t\t}\n\t\tif path, ok := trasport[\"path\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"path\", path})\n\t\t}\n\tcase \"ws\":\n\t\tif path, ok := trasport[\"path\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"path\", path})\n\t\t}\n\t\tif headers, ok := trasport[\"headers\"].(map[string]interface{}); ok {\n\t\t\tif host, ok := headers[\"Host\"].(string); ok {\n\t\t\t\tparams = append(params, LinkParam{\"host\", host})\n\t\t\t}\n\t\t}\n\tcase \"grpc\":\n\t\tif serviceName, ok := trasport[\"service_name\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"serviceName\", serviceName})\n\t\t}\n\tcase \"httpupgrade\":\n\t\tif host, ok := trasport[\"host\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"host\", host})\n\t\t}\n\t\tif path, ok := trasport[\"path\"].(string); ok {\n\t\t\tparams = append(params, LinkParam{\"path\", path})\n\t\t}\n\t}\n\treturn params\n}\n\nfunc getTlsParams(params *[]LinkParam, tls map[string]interface{}, insecureKey string) {\n\tif reality, ok := tls[\"reality\"].(map[string]interface{}); ok && reality[\"enabled\"].(bool) {\n\t\t*params = append(*params, LinkParam{\"security\", \"reality\"})\n\t\tif pbk, ok := reality[\"public_key\"].(string); ok {\n\t\t\t*params = append(*params, LinkParam{\"pbk\", pbk})\n\t\t}\n\t\tif sid, ok := reality[\"short_id\"].(string); ok {\n\t\t\t*params = append(*params, LinkParam{\"sid\", sid})\n\t\t}\n\t} else {\n\t\t*params = append(*params, LinkParam{\"security\", \"tls\"})\n\t\tif insecure, ok := tls[\"insecure\"].(bool); ok && insecure {\n\t\t\t*params = append(*params, LinkParam{insecureKey, \"1\"})\n\t\t}\n\t\tif disableSni, ok := tls[\"disable_sni\"].(bool); ok && disableSni {\n\t\t\t*params = append(*params, LinkParam{\"disable_sni\", \"1\"})\n\t\t}\n\t}\n\tif utls, ok := tls[\"utls\"].(map[string]interface{}); ok {\n\t\tif fingerprint, ok := utls[\"fingerprint\"].(string); ok {\n\t\t\t*params = append(*params, LinkParam{\"fp\", fingerprint})\n\t\t}\n\t}\n\tif sni, ok := tls[\"server_name\"].(string); ok {\n\t\t*params = append(*params, LinkParam{\"sni\", sni})\n\t}\n\tif alpn, ok := tls[\"alpn\"].([]interface{}); ok {\n\t\talpnList := make([]string, len(alpn))\n\t\tfor i, v := range alpn {\n\t\t\talpnList[i] = v.(string)\n\t\t}\n\t\t*params = append(*params, LinkParam{\"alpn\", strings.Join(alpnList, \",\")})\n\t}\n}\n"
  },
  {
    "path": "util/linkToJson.go",
    "content": "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/common\"\n)\n\nfunc GetOutbound(uri string, i int) (*map[string]interface{}, string, error) {\n\tu, err := url.Parse(uri)\n\tif err == nil {\n\t\tswitch u.Scheme {\n\t\tcase \"vmess\":\n\t\t\treturn vmess(u.Host, i)\n\t\tcase \"vless\":\n\t\t\treturn vless(u, i)\n\t\tcase \"trojan\":\n\t\t\treturn trojan(u, i)\n\t\tcase \"hy\", \"hysteria\":\n\t\t\treturn hy(u, i)\n\t\tcase \"hy2\", \"hysteria2\":\n\t\t\treturn hy2(u, i)\n\t\tcase \"anytls\":\n\t\t\treturn anytls(u, i)\n\t\tcase \"tuic\":\n\t\t\treturn tuic(u, i)\n\t\tcase \"ss\", \"shadowsocks\":\n\t\t\treturn ss(u, i)\n\t\tcase \"naive+https\", \"naive+quic\", \"http2\":\n\t\t\treturn parseNaiveLink(u, i)\n\t\t}\n\t}\n\treturn nil, \"\", common.NewError(\"Unsupported link format\")\n}\n\nfunc vmess(data string, i int) (*map[string]interface{}, string, error) {\n\tdataByte, err := B64StrToByte(data)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tvar dataJson map[string]interface{}\n\terr = json.Unmarshal(dataByte, &dataJson)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\ttransport := map[string]interface{}{}\n\ttp_net, _ := dataJson[\"net\"].(string)\n\ttp_type, _ := dataJson[\"type\"].(string)\n\ttp_host, _ := dataJson[\"host\"].(string)\n\ttp_path, _ := dataJson[\"path\"].(string)\n\tswitch strings.ToLower(tp_net) {\n\tcase \"tcp\", \"\":\n\t\tif tp_type == \"http\" {\n\t\t\ttransport[\"type\"] = tp_type\n\t\t\tif len(tp_host) > 0 {\n\t\t\t\ttransport[\"host\"] = strings.Split(tp_host, \",\")\n\t\t\t}\n\t\t\ttransport[\"path\"] = tp_path\n\t\t}\n\tcase \"http\", \"h2\":\n\t\ttransport[\"type\"] = \"http\"\n\t\tif len(tp_host) > 0 {\n\t\t\ttransport[\"host\"] = strings.Split(tp_host, \",\")\n\t\t}\n\t\ttransport[\"path\"] = tp_path\n\tcase \"ws\":\n\t\ttransport[\"type\"] = tp_net\n\t\ttransport[\"path\"] = tp_path\n\t\ttransport[\"early_data_header_name\"] = \"Sec-WebSocket-Protocol\"\n\t\tif len(tp_host) > 0 {\n\t\t\ttransport[\"headers\"] = map[string]interface{}{\n\t\t\t\t\"Host\": tp_host,\n\t\t\t}\n\t\t}\n\tcase \"quic\":\n\t\ttransport[\"type\"] = tp_net\n\tcase \"grpc\":\n\t\ttransport[\"type\"] = tp_net\n\t\ttransport[\"service_name\"] = tp_path\n\tcase \"httpupgrade\":\n\t\ttransport[\"type\"] = tp_net\n\t\ttransport[\"path\"] = tp_path\n\t\ttransport[\"host\"] = tp_host\n\tdefault:\n\t\treturn nil, \"\", common.NewError(\"Invalid vmess\")\n\t}\n\ttls := map[string]interface{}{}\n\tvmess_tls, _ := dataJson[\"tls\"].(string)\n\tif vmess_tls == \"tls\" {\n\t\ttls[\"enabled\"] = true\n\t\ttls_sni, _ := dataJson[\"sni\"].(string)\n\t\ttls_alpn, _ := dataJson[\"alpn\"].(string)\n\t\t_, tls_insecure := dataJson[\"allowInsecure\"]\n\t\ttls_fp, _ := dataJson[\"fp\"].(string)\n\t\tif len(tls_sni) > 0 {\n\t\t\ttls[\"server_name\"] = tls_sni\n\t\t}\n\t\tif len(tls_alpn) > 0 {\n\t\t\ttls[\"alpn\"] = strings.Split(tls_alpn, \",\")\n\t\t}\n\t\tif tls_insecure {\n\t\t\ttls[\"insecure\"] = true\n\t\t}\n\t\tif len(tls_fp) > 0 {\n\t\t\ttls[\"utls\"] = map[string]interface{}{\n\t\t\t\t\"enabled\":     true,\n\t\t\t\t\"fingerprint\": tls_fp,\n\t\t\t}\n\t\t}\n\t}\n\ttag, _ := dataJson[\"ps\"].(string)\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, tag)\n\t}\n\talter_id := 0\n\tif aid, ok := dataJson[\"aid\"].(float64); ok {\n\t\talter_id = int(aid)\n\t}\n\tvmess := map[string]interface{}{\n\t\t\"type\":        \"vmess\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      dataJson[\"add\"],\n\t\t\"server_port\": dataJson[\"port\"],\n\t\t\"uuid\":        dataJson[\"id\"],\n\t\t\"security\":    \"auto\",\n\t\t\"alter_id\":    alter_id,\n\t\t\"tls\":         tls,\n\t\t\"transport\":   transport,\n\t}\n\treturn &vmess, tag, err\n}\n\nfunc vless(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\tsecurity := query.Get(\"security\")\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 80\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t} else {\n\t\tif security == \"tls\" || security == \"reality\" {\n\t\t\tport = 443\n\t\t}\n\t}\n\ttp_type := query.Get(\"type\")\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\tvless := map[string]interface{}{\n\t\t\"type\":        \"vless\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"uuid\":        u.User.Username(),\n\t\t\"flow\":        query.Get(\"flow\"),\n\t\t\"tls\":         getTls(security, &query),\n\t\t\"transport\":   getTransport(tp_type, &query),\n\t}\n\treturn &vless, tag, nil\n}\n\nfunc trojan(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\tsecurity := query.Get(\"security\")\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 80\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t} else {\n\t\tif security == \"tls\" || security == \"reality\" {\n\t\t\tport = 443\n\t\t}\n\t}\n\ttp_type := query.Get(\"type\")\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\ttrojan := map[string]interface{}{\n\t\t\"type\":        \"trojan\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"password\":    u.User.Username(),\n\t\t\"tls\":         getTls(security, &query),\n\t\t\"transport\":   getTransport(tp_type, &query),\n\t}\n\treturn &trojan, tag, nil\n}\n\nfunc hy(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 443\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t}\n\n\tsecurity := query.Get(\"security\")\n\tif len(security) == 0 {\n\t\tsecurity = \"tls\"\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\thy := map[string]interface{}{\n\t\t\"type\":        \"hysteria\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"obfs\":        query.Get(\"obfsParam\"),\n\t\t\"auth_str\":    query.Get(\"auth\"),\n\t\t\"tls\":         getTls(security, &query),\n\t}\n\tdown, _ := strconv.Atoi(query.Get(\"downmbps\"))\n\tup, _ := strconv.Atoi(query.Get(\"upmbps\"))\n\trecv_window_conn, _ := strconv.Atoi(query.Get(\"recv_window_conn\"))\n\trecv_window, _ := strconv.Atoi(query.Get(\"recv_window\"))\n\tif down > 0 {\n\t\thy[\"down_mbps\"] = down\n\t}\n\tif up > 0 {\n\t\thy[\"up_mbps\"] = up\n\t}\n\tif recv_window_conn > 0 {\n\t\thy[\"recv_window_conn\"] = recv_window_conn\n\t}\n\tif recv_window > 0 {\n\t\thy[\"recv_window\"] = recv_window\n\t}\n\treturn &hy, tag, nil\n}\n\nfunc hy2(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 443\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t}\n\n\tsecurity := query.Get(\"security\")\n\tif len(security) == 0 {\n\t\tsecurity = \"tls\"\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\thy2 := map[string]interface{}{\n\t\t\"type\":        \"hysteria2\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"password\":    u.User.Username(),\n\t\t\"tls\":         getTls(security, &query),\n\t}\n\tdown, _ := strconv.Atoi(query.Get(\"downmbps\"))\n\tup, _ := strconv.Atoi(query.Get(\"upmbps\"))\n\tobfs := query.Get(\"obfs\")\n\tmport := query.Get(\"mport\")\n\tfastopen := query.Get(\"fastopen\")\n\tif down > 0 {\n\t\thy2[\"down_mbps\"] = down\n\t}\n\tif up > 0 {\n\t\thy2[\"up_mbps\"] = up\n\t}\n\tif obfs == \"salamander\" {\n\t\thy2[\"obfs\"] = map[string]interface{}{\n\t\t\t\"type\":     \"salamander\",\n\t\t\t\"password\": query.Get(\"obfs-password\"),\n\t\t}\n\t}\n\tif len(mport) > 0 {\n\t\thy2[\"server_ports\"] = strings.Split(mport, \",\")\n\t}\n\tif fastopen == \"1\" || fastopen == \"true\" {\n\t\thy2[\"fastopen\"] = true\n\t}\n\treturn &hy2, tag, nil\n}\n\nfunc anytls(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 443\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t}\n\n\tsecurity := query.Get(\"security\")\n\tif len(security) == 0 {\n\t\tsecurity = \"tls\"\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\tanytls := map[string]interface{}{\n\t\t\"type\":        \"anytls\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"password\":    u.User.Username(),\n\t\t\"tls\":         getTls(security, &query),\n\t}\n\treturn &anytls, tag, nil\n}\n\nfunc tuic(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 443\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t}\n\n\tsecurity := query.Get(\"security\")\n\tif len(security) == 0 {\n\t\tsecurity = \"tls\"\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\tpassword, _ := u.User.Password()\n\ttuic := map[string]interface{}{\n\t\t\"type\":               \"tuic\",\n\t\t\"tag\":                tag,\n\t\t\"server\":             host,\n\t\t\"server_port\":        port,\n\t\t\"uuid\":               u.User.Username(),\n\t\t\"password\":           password,\n\t\t\"congestion_control\": query.Get(\"congestion_control\"),\n\t\t\"udp_relay_mode\":     query.Get(\"udp_relay_mode\"),\n\t\t\"tls\":                getTls(security, &query),\n\t}\n\treturn &tuic, tag, nil\n}\n\nfunc ss(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tquery, _ := url.ParseQuery(u.RawQuery)\n\thost, portStr, _ := net.SplitHostPort(u.Host)\n\tport := 443\n\tif len(portStr) > 0 {\n\t\tport, _ = strconv.Atoi(portStr)\n\t}\n\tmethod := u.User.Username()\n\tpassword, ok := u.User.Password()\n\tif !ok {\n\t\tdecrypted := StrOrBase64Encoded(method)\n\t\tdecrypted_arr := strings.Split(decrypted, \":\")\n\t\tif len(decrypted_arr) > 1 {\n\t\t\tmethod = decrypted_arr[0]\n\t\t\tpassword = strings.Join(decrypted_arr[1:], \":\")\n\t\t} else {\n\t\t\treturn nil, \"\", common.NewError(\"Unsupported shadowsocks\")\n\t\t}\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\tss := map[string]interface{}{\n\t\t\"type\":        \"shadowsocks\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"method\":      method,\n\t\t\"password\":    password,\n\t}\n\n\tv2ray_type := query.Get(\"type\")\n\tif len(v2ray_type) > 0 {\n\t\tpl_arr := []string{}\n\t\thost_header := query.Get(\"host\")\n\t\tif query.Get(\"security\") == \"tls\" {\n\t\t\tpl_arr = append(pl_arr, \"tls\")\n\t\t}\n\t\tif v2ray_type == \"quic\" {\n\t\t\tpl_arr = append(pl_arr, \"mode=quic\")\n\t\t}\n\t\tif len(host_header) > 0 {\n\t\t\tpl_arr = append(pl_arr, \"host=\"+host_header)\n\t\t}\n\t\tss[\"plugin\"] = \"v2ray-plugin\"\n\t\tss[\"plugin_opts\"] = strings.Join(pl_arr, \";\")\n\t}\n\tplugin := query.Get(\"plugin\")\n\tif len(plugin) > 0 {\n\t\tpl_arr := strings.Split(plugin, \";\")\n\t\tif len(pl_arr) > 0 {\n\t\t\tss[\"plugin\"] = pl_arr[0]\n\t\t\tss[\"plugin_opts\"] = strings.Join(pl_arr[1:], \";\")\n\t\t}\n\t}\n\treturn &ss, tag, nil\n}\n\nfunc parseNaiveLink(u *url.URL, i int) (*map[string]interface{}, string, error) {\n\tvar host, portStr, username, password string\n\tvar port int\n\n\tswitch u.Scheme {\n\tcase \"http2\":\n\t\tdecoded := StrOrBase64Encoded(u.Hostname())\n\t\tif idx := strings.Index(decoded, \"@\"); idx != -1 {\n\t\t\tuserInfo := decoded[:idx]\n\t\t\thostPort := decoded[idx+1:]\n\t\t\tif idx2 := strings.Index(userInfo, \":\"); idx2 != -1 {\n\t\t\t\tusername = userInfo[:idx2]\n\t\t\t\tpassword = userInfo[idx2+1:]\n\t\t\t} else {\n\t\t\t\tusername = userInfo\n\t\t\t}\n\t\t\thost, portStr, _ = net.SplitHostPort(hostPort)\n\t\t\tif portStr != \"\" {\n\t\t\t\tport, _ = strconv.Atoi(portStr)\n\t\t\t} else {\n\t\t\t\tport = 443\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, \"\", common.NewError(\"Invalid naive link (http2)\")\n\t\t}\n\tcase \"naive+https\", \"naive+quic\":\n\t\thost, portStr, _ = net.SplitHostPort(u.Host)\n\t\tif portStr != \"\" {\n\t\t\tport, _ = strconv.Atoi(portStr)\n\t\t} else {\n\t\t\tport = 443\n\t\t}\n\t\tif u.User != nil {\n\t\t\tusername = u.User.Username()\n\t\t\tpassword, _ = u.User.Password()\n\t\t}\n\tdefault:\n\t\treturn nil, \"\", common.NewError(\"Unsupported naive scheme\")\n\t}\n\n\ttag := u.Fragment\n\tif i > 0 {\n\t\ttag = fmt.Sprintf(\"%d.%s\", i, u.Fragment)\n\t}\n\tif tag == \"\" {\n\t\ttag = fmt.Sprintf(\"naive-%d\", i)\n\t}\n\n\tnaive := map[string]interface{}{\n\t\t\"type\":        \"naive\",\n\t\t\"tag\":         tag,\n\t\t\"server\":      host,\n\t\t\"server_port\": port,\n\t\t\"username\":    username,\n\t\t\"password\":    password,\n\t\t\"tls\":         map[string]interface{}{\"enabled\": true},\n\t}\n\n\tquery := u.Query()\n\tif peer := query.Get(\"peer\"); peer != \"\" {\n\t\tif tls, ok := naive[\"tls\"].(map[string]interface{}); ok {\n\t\t\ttls[\"server_name\"] = peer\n\t\t}\n\t}\n\tif insecure := query.Get(\"insecure\"); insecure == \"1\" || insecure == \"true\" {\n\t\tif tls, ok := naive[\"tls\"].(map[string]interface{}); ok {\n\t\t\ttls[\"insecure\"] = true\n\t\t}\n\t}\n\tif alpn := query.Get(\"alpn\"); alpn != \"\" {\n\t\tif tls, ok := naive[\"tls\"].(map[string]interface{}); ok {\n\t\t\ttls[\"alpn\"] = strings.Split(alpn, \",\")\n\t\t}\n\t}\n\tif u.Scheme == \"naive+quic\" {\n\t\tnaive[\"quic\"] = true\n\t}\n\n\treturn &naive, tag, nil\n}\n\nfunc getTransport(tp_type string, q *url.Values) map[string]interface{} {\n\ttransport := map[string]interface{}{}\n\ttp_host := q.Get(\"host\")\n\ttp_path := q.Get(\"path\")\n\tswitch strings.ToLower(tp_type) {\n\tcase \"tcp\", \"\":\n\t\tif q.Get(\"headerType\") == \"http\" {\n\t\t\ttransport[\"type\"] = \"http\"\n\t\t\tif len(tp_host) > 0 {\n\t\t\t\ttransport[\"host\"] = strings.Split(tp_host, \",\")\n\t\t\t}\n\t\t\ttransport[\"path\"] = tp_path\n\t\t}\n\tcase \"http\", \"h2\":\n\t\ttransport[\"type\"] = \"http\"\n\t\tif len(tp_host) > 0 {\n\t\t\ttransport[\"host\"] = strings.Split(tp_host, \",\")\n\t\t}\n\t\ttransport[\"path\"] = tp_path\n\tcase \"ws\":\n\t\ttransport[\"type\"] = \"ws\"\n\t\ttransport[\"path\"] = tp_path\n\t\tif len(tp_host) > 0 {\n\t\t\ttransport[\"headers\"] = map[string]interface{}{\n\t\t\t\t\"Host\": tp_host,\n\t\t\t}\n\t\t}\n\tcase \"quic\":\n\t\ttransport[\"type\"] = \"quic\"\n\tcase \"grpc\":\n\t\ttransport[\"type\"] = \"grpc\"\n\t\ttransport[\"service_name\"] = q.Get(\"serviceName\")\n\tcase \"httpupgrade\":\n\t\ttransport[\"type\"] = \"httpupgrade\"\n\t\ttransport[\"path\"] = tp_path\n\t\ttransport[\"host\"] = tp_host\n\t}\n\treturn transport\n}\n\nfunc getTls(security string, q *url.Values) map[string]interface{} {\n\ttls := map[string]interface{}{}\n\ttls_fp := q.Get(\"fp\")\n\ttls_sni := q.Get(\"sni\")\n\ttls_allow_insecure := q.Get(\"allowInsecure\")\n\ttls_insecure := q.Get(\"insecure\")\n\ttls_alpn := q.Get(\"alpn\")\n\ttls_ech := q.Get(\"ech\")\n\tdisable_sni := q.Get(\"disable_sni\")\n\tswitch security {\n\tcase \"tls\":\n\t\ttls[\"enabled\"] = true\n\tcase \"reality\":\n\t\ttls[\"enabled\"] = true\n\t\ttls[\"reality\"] = map[string]interface{}{\n\t\t\t\"enabled\":    true,\n\t\t\t\"public_key\": q.Get(\"pbk\"),\n\t\t\t\"short_id\":   q.Get(\"sid\"),\n\t\t}\n\t}\n\tif len(tls_sni) > 0 {\n\t\ttls[\"server_name\"] = tls_sni\n\t}\n\tif len(tls_alpn) > 0 {\n\t\ttls[\"alpn\"] = strings.Split(tls_alpn, \",\")\n\t}\n\tif tls_insecure == \"1\" || tls_insecure == \"true\" || tls_allow_insecure == \"1\" || tls_allow_insecure == \"true\" {\n\t\ttls[\"insecure\"] = true\n\t}\n\tif len(tls_fp) > 0 {\n\t\ttls[\"utls\"] = map[string]interface{}{\n\t\t\t\"enabled\":     true,\n\t\t\t\"fingerprint\": tls_fp,\n\t\t}\n\t}\n\tif len(tls_ech) > 0 {\n\t\ttls[\"ech\"] = map[string]interface{}{\n\t\t\t\"enabled\": true,\n\t\t\t\"config\": []string{\n\t\t\t\ttls_ech,\n\t\t\t},\n\t\t}\n\t}\n\tif disable_sni == \"1\" || disable_sni == \"true\" {\n\t\ttls[\"disable_sni\"] = true\n\t}\n\treturn tls\n}\n"
  },
  {
    "path": "util/outJson.go",
    "content": "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/model\"\n)\n\n// Fill Inbound's out_json\nfunc FillOutJson(i *model.Inbound, hostname string) error {\n\tswitch i.Type {\n\tcase \"direct\", \"tun\", \"redirect\", \"tproxy\":\n\t\treturn nil\n\t}\n\tvar outJson map[string]interface{}\n\terr := json.Unmarshal(i.OutJson, &outJson)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif outJson == nil {\n\t\toutJson = make(map[string]interface{})\n\t}\n\n\tif i.TlsId > 0 {\n\t\taddTls(&outJson, i.Tls)\n\t} else {\n\t\tdelete(outJson, \"tls\")\n\t}\n\n\tinbound, err := i.MarshalFull()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutJson[\"type\"] = i.Type\n\toutJson[\"tag\"] = i.Tag\n\toutJson[\"server\"] = hostname\n\toutJson[\"server_port\"] = (*inbound)[\"listen_port\"]\n\n\tswitch i.Type {\n\tcase \"http\", \"socks\", \"mixed\", \"anytls\":\n\tcase \"naive\":\n\t\tnaiveOut(&outJson, *inbound)\n\tcase \"shadowsocks\":\n\t\tshadowsocksOut(&outJson, *inbound)\n\tcase \"shadowtls\":\n\t\tshadowTlsOut(&outJson, *inbound)\n\tcase \"hysteria\":\n\t\thysteriaOut(&outJson, *inbound)\n\tcase \"hysteria2\":\n\t\thysteria2Out(&outJson, *inbound)\n\tcase \"tuic\":\n\t\ttuicOut(&outJson, *inbound)\n\tcase \"vless\":\n\t\tvlessOut(&outJson, *inbound)\n\tcase \"trojan\":\n\t\ttrojanOut(&outJson, *inbound)\n\tcase \"vmess\":\n\t\tvmessOut(&outJson, *inbound)\n\tdefault:\n\t\tfor key := range outJson {\n\t\t\tdelete(outJson, key)\n\t\t}\n\t}\n\n\ti.OutJson, err = json.MarshalIndent(outJson, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// addTls function\nfunc addTls(out *map[string]interface{}, tls *model.Tls) {\n\tvar tlsServer, tlsConfig map[string]interface{}\n\terr := json.Unmarshal(tls.Server, &tlsServer)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(tls.Client, &tlsConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif enabled, ok := tlsServer[\"enabled\"]; ok {\n\t\ttlsConfig[\"enabled\"] = enabled\n\t}\n\tif serverName, ok := tlsServer[\"server_name\"]; ok {\n\t\ttlsConfig[\"server_name\"] = serverName\n\t}\n\tif alpn, ok := tlsServer[\"alpn\"]; ok {\n\t\ttlsConfig[\"alpn\"] = alpn\n\t}\n\tif minVersion, ok := tlsServer[\"min_version\"]; ok {\n\t\ttlsConfig[\"min_version\"] = minVersion\n\t}\n\tif maxVersion, ok := tlsServer[\"max_version\"]; ok {\n\t\ttlsConfig[\"max_version\"] = maxVersion\n\t}\n\tif certificate, ok := tlsServer[\"certificate\"]; ok {\n\t\ttlsConfig[\"certificate\"] = certificate\n\t}\n\tif cipherSuites, ok := tlsServer[\"cipher_suites\"]; ok {\n\t\ttlsConfig[\"cipher_suites\"] = cipherSuites\n\t}\n\tif reality, ok := tlsServer[\"reality\"].(map[string]interface{}); ok && reality[\"enabled\"].(bool) {\n\t\trealityConfig := tlsConfig[\"reality\"].(map[string]interface{})\n\t\trealityConfig[\"enabled\"] = true\n\t\tif shortIDs, ok := reality[\"short_id\"].([]interface{}); ok && len(shortIDs) > 0 {\n\t\t\trealityConfig[\"short_id\"] = shortIDs[common.RandomInt(len(shortIDs))]\n\t\t}\n\t\ttlsConfig[\"reality\"] = realityConfig\n\t}\n\tif ech, ok := tlsServer[\"ech\"].(map[string]interface{}); ok && ech[\"enabled\"].(bool) {\n\t\techConfig := tlsConfig[\"ech\"].(map[string]interface{})\n\t\techConfig[\"enabled\"] = true\n\t\techConfig[\"pq_signature_schemes_enabled\"] = ech[\"pq_signature_schemes_enabled\"]\n\t\techConfig[\"dynamic_record_sizing_disabled\"] = ech[\"dynamic_record_sizing_disabled\"]\n\t\ttlsConfig[\"ech\"] = echConfig\n\t}\n\n\t(*out)[\"tls\"] = tlsConfig\n}\n\nfunc naiveOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tif quic_congestion_control, ok := inbound[\"quic_congestion_control\"].(string); ok {\n\t\t(*out)[\"quic\"] = true\n\t\tswitch quic_congestion_control {\n\t\tcase \"bbr_standard\":\n\t\t\t(*out)[\"quic_congestion_control\"] = \"bbr\"\n\t\tcase \"bbr2_variant\":\n\t\t\t(*out)[\"quic_congestion_control\"] = \"bbr2\"\n\t\tdefault:\n\t\t\t(*out)[\"quic_congestion_control\"] = quic_congestion_control\n\t\t}\n\t}\n\n}\n\nfunc shadowsocksOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tif method, ok := inbound[\"method\"].(string); ok {\n\t\t(*out)[\"method\"] = method\n\t}\n}\n\nfunc shadowTlsOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tif version, ok := inbound[\"version\"].(float64); ok && int(version) == 3 {\n\t\t(*out)[\"version\"] = 3\n\t} else {\n\t\tfor key := range *out {\n\t\t\tdelete(*out, key)\n\t\t}\n\t}\n\t(*out)[\"tls\"] = map[string]interface{}{\"enabled\": true}\n}\n\nfunc hysteriaOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tdelete(*out, \"down_mbps\")\n\tdelete(*out, \"up_mbps\")\n\tdelete(*out, \"obfs\")\n\tdelete(*out, \"recv_window_conn\")\n\tdelete(*out, \"disable_mtu_discovery\")\n\n\tif upMbps, ok := inbound[\"down_mbps\"]; ok {\n\t\t(*out)[\"up_mbps\"] = upMbps\n\t}\n\tif downMbps, ok := inbound[\"up_mbps\"]; ok {\n\t\t(*out)[\"down_mbps\"] = downMbps\n\t}\n\tif obfs, ok := inbound[\"obfs\"]; ok {\n\t\t(*out)[\"obfs\"] = obfs\n\t}\n\tif recvWindow, ok := inbound[\"recv_window_conn\"]; ok {\n\t\t(*out)[\"recv_window_conn\"] = recvWindow\n\t}\n\tif disableMTU, ok := inbound[\"disable_mtu_discovery\"]; ok {\n\t\t(*out)[\"disable_mtu_discovery\"] = disableMTU\n\t}\n}\n\nfunc hysteria2Out(out *map[string]interface{}, inbound map[string]interface{}) {\n\tdelete(*out, \"down_mbps\")\n\tdelete(*out, \"up_mbps\")\n\tdelete(*out, \"obfs\")\n\n\tif upMbps, ok := inbound[\"down_mbps\"]; ok {\n\t\t(*out)[\"up_mbps\"] = upMbps\n\t}\n\tif downMbps, ok := inbound[\"up_mbps\"]; ok {\n\t\t(*out)[\"down_mbps\"] = downMbps\n\t}\n\tif obfs, ok := inbound[\"obfs\"]; ok {\n\t\t(*out)[\"obfs\"] = obfs\n\t}\n}\n\nfunc tuicOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tdelete(*out, \"zero_rtt_handshake\")\n\tdelete(*out, \"heartbeat\")\n\tif congestionControl, ok := inbound[\"congestion_control\"].(string); ok {\n\t\t(*out)[\"congestion_control\"] = congestionControl\n\t} else {\n\t\t(*out)[\"congestion_control\"] = \"cubic\"\n\t}\n\tif zeroRTT, ok := inbound[\"zero_rtt_handshake\"].(bool); ok {\n\t\t(*out)[\"zero_rtt_handshake\"] = zeroRTT\n\t}\n\tif heartbeat, ok := inbound[\"heartbeat\"]; ok {\n\t\t(*out)[\"heartbeat\"] = heartbeat\n\t}\n}\n\nfunc vlessOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tdelete(*out, \"transport\")\n\tif transport, ok := inbound[\"transport\"]; ok {\n\t\t(*out)[\"transport\"] = transport\n\t}\n}\n\nfunc trojanOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\tdelete(*out, \"transport\")\n\tif transport, ok := inbound[\"transport\"]; ok {\n\t\t(*out)[\"transport\"] = transport\n\t}\n}\n\nfunc vmessOut(out *map[string]interface{}, inbound map[string]interface{}) {\n\t(*out)[\"alter_id\"] = 0\n\tdelete(*out, \"transport\")\n\tif transport, ok := inbound[\"transport\"]; ok {\n\t\t(*out)[\"transport\"] = transport\n\t}\n}\n"
  },
  {
    "path": "util/subInfo.go",
    "content": "package util\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/alireza0/s-ui/database/model\"\n)\n\nfunc GetHeaders(client *model.Client, updateInterval int) []string {\n\tvar headers []string\n\theaders = append(headers, fmt.Sprintf(\"upload=%d; download=%d; total=%d; expire=%d\", client.Up, client.Down, client.Volume, client.Expiry))\n\theaders = append(headers, fmt.Sprintf(\"%d\", updateInterval))\n\theaders = append(headers, client.Name)\n\treturn headers\n}\n"
  },
  {
    "path": "util/subToJson.go",
    "content": "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\"github.com/alireza0/s-ui/util/common\"\n)\n\nfunc GetExternalLink(url string) string {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\n\tclient := &http.Client{Transport: tr}\n\n\tresponse, err := client.Get(url)\n\tif err != nil {\n\t\tlogger.Warning(\"sub: Error making HTTP request:\", err)\n\t\treturn \"\"\n\t}\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\tlogger.Warning(\"sub: Error reading response body:\", err)\n\t\treturn \"\"\n\t}\n\n\tdata := StrOrBase64Encoded(string(body))\n\treturn data\n}\n\nfunc GetExternalSub(url string) ([]map[string]interface{}, error) {\n\tvar err error\n\tvar result []map[string]interface{}\n\n\tif len(url) == 0 {\n\t\treturn nil, common.NewError(\"no url\")\n\t}\n\n\tdata := GetExternalLink(url)\n\tif len(data) == 0 {\n\t\treturn nil, common.NewError(\"no result\")\n\t}\n\n\t// if the data is a JSON object\n\tif strings.HasPrefix(data, \"{\") && strings.HasSuffix(data, \"}\") {\n\t\tvar jsonData map[string]interface{}\n\t\terr = json.Unmarshal([]byte(data), &jsonData)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"sub: Error unmarshalling JSON:\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\toutbounds, ok := jsonData[\"outbounds\"].([]any)\n\t\tif !ok {\n\t\t\tlogger.Warning(\"sub: Error getting outbounds:\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, outbound := range outbounds {\n\t\t\toutboundMap, ok := outbound.(map[string]interface{})\n\t\t\tif ok && len(outboundMap) > 0 {\n\t\t\t\toType, _ := outboundMap[\"type\"].(string)\n\t\t\t\tswitch oType {\n\t\t\t\tcase \"urltest\":\n\t\t\t\tcase \"direct\":\n\t\t\t\tcase \"selector\":\n\t\t\t\tcase \"block\":\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tresult = append(result, outboundMap)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(result) == 0 {\n\t\t\treturn nil, common.NewError(\"no result\")\n\t\t}\n\t\treturn result, nil\n\t} else {\n\t\t// if data is a text\n\t\tlinks := strings.Split(data, \"\\n\")\n\t\tfor _, link := range links {\n\t\t\tlinkToJson, _, err := GetOutbound(link, 0)\n\t\t\tif err == nil {\n\t\t\t\tresult = append(result, *linkToJson)\n\t\t\t}\n\t\t}\n\t}\n\tif len(result) == 0 {\n\t\treturn nil, common.NewError(\"no result\")\n\t}\n\treturn result, nil\n}\n"
  },
  {
    "path": "web/web.go",
    "content": "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\"strings\"\n\n\t\"github.com/alireza0/s-ui/api\"\n\t\"github.com/alireza0/s-ui/config\"\n\t\"github.com/alireza0/s-ui/logger\"\n\t\"github.com/alireza0/s-ui/middleware\"\n\t\"github.com/alireza0/s-ui/network\"\n\t\"github.com/alireza0/s-ui/service\"\n\n\t\"github.com/gin-contrib/gzip\"\n\t\"github.com/gin-contrib/sessions\"\n\t\"github.com/gin-contrib/sessions/cookie\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n//go:embed *\nvar content embed.FS\n\ntype Server struct {\n\thttpServer     *http.Server\n\tlistener       net.Listener\n\tctx            context.Context\n\tcancel         context.CancelFunc\n\tsettingService service.SettingService\n}\n\nfunc NewServer() *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n}\n\nfunc (s *Server) initRouter() (*gin.Engine, error) {\n\tif config.IsDebug() {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.DefaultWriter = io.Discard\n\t\tgin.DefaultErrorWriter = io.Discard\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\tengine := gin.Default()\n\n\t// Load the HTML template\n\tt := template.New(\"\").Funcs(engine.FuncMap)\n\ttemplate, err := t.ParseFS(content, \"html/index.html\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tengine.SetHTMLTemplate(template)\n\n\tbase_url, err := s.settingService.GetWebPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twebDomain, err := s.settingService.GetWebDomain()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif webDomain != \"\" {\n\t\tengine.Use(middleware.DomainValidator(webDomain))\n\t}\n\n\tsecret, err := s.settingService.GetSecret()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tengine.Use(gzip.Gzip(gzip.DefaultCompression))\n\tassetsBasePath := base_url + \"assets/\"\n\n\tstore := cookie.NewStore(secret)\n\tengine.Use(sessions.Sessions(\"s-ui\", store))\n\n\tengine.Use(func(c *gin.Context) {\n\t\turi := c.Request.RequestURI\n\t\tif strings.HasPrefix(uri, assetsBasePath) {\n\t\t\tc.Header(\"Cache-Control\", \"max-age=31536000\")\n\t\t}\n\t})\n\n\t// Serve the assets folder\n\tassetsFS, err := fs.Sub(content, \"html/assets\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tengine.StaticFS(assetsBasePath, http.FS(assetsFS))\n\n\tgroup_apiv2 := engine.Group(base_url + \"apiv2\")\n\tapiv2 := api.NewAPIv2Handler(group_apiv2)\n\n\tgroup_api := engine.Group(base_url + \"api\")\n\tapi.NewAPIHandler(group_api, apiv2)\n\n\t// Serve index.html as the entry point\n\t// Handle all other routes by serving index.html\n\tengine.NoRoute(func(c *gin.Context) {\n\t\tif c.Request.URL.Path == strings.TrimSuffix(base_url, \"/\") {\n\t\t\tc.Redirect(http.StatusTemporaryRedirect, base_url)\n\t\t\treturn\n\t\t}\n\t\tif !strings.HasPrefix(c.Request.URL.Path, base_url) {\n\t\t\tc.String(404, \"\")\n\t\t\treturn\n\t\t}\n\t\tif c.Request.URL.Path != base_url+\"login\" && !api.IsLogin(c) {\n\t\t\tc.Redirect(http.StatusTemporaryRedirect, base_url+\"login\")\n\t\t\treturn\n\t\t}\n\t\tif c.Request.URL.Path == base_url+\"login\" && api.IsLogin(c) {\n\t\t\tc.Redirect(http.StatusTemporaryRedirect, base_url)\n\t\t\treturn\n\t\t}\n\t\tc.HTML(http.StatusOK, \"index.html\", gin.H{\"BASE_URL\": base_url})\n\t})\n\n\treturn engine, nil\n}\n\nfunc (s *Server) Start() (err error) {\n\t//This is an anonymous function, no function name\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ts.Stop()\n\t\t}\n\t}()\n\n\tengine, err := s.initRouter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcertFile, err := s.settingService.GetCertFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tkeyFile, err := s.settingService.GetKeyFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlisten, err := s.settingService.GetListen()\n\tif err != nil {\n\t\treturn err\n\t}\n\tport, err := s.settingService.GetPort()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistenAddr := net.JoinHostPort(listen, strconv.Itoa(port))\n\tlistener, err := net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif certFile != \"\" || keyFile != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\treturn err\n\t\t}\n\t\tc := &tls.Config{\n\t\t\tCertificates: []tls.Certificate{cert},\n\t\t}\n\t\tlistener = network.NewAutoHttpsListener(listener)\n\t\tlistener = tls.NewListener(listener, c)\n\t}\n\n\tif certFile != \"\" || keyFile != \"\" {\n\t\tlogger.Info(\"web server run https on\", listener.Addr())\n\t} else {\n\t\tlogger.Info(\"web server run http on\", listener.Addr())\n\t}\n\ts.listener = listener\n\n\ts.httpServer = &http.Server{\n\t\tHandler: engine,\n\t}\n\n\tgo func() {\n\t\ts.httpServer.Serve(listener)\n\t}()\n\n\treturn nil\n}\n\nfunc (s *Server) Stop() error {\n\ts.cancel()\n\tvar err error\n\tif s.httpServer != nil {\n\t\terr = s.httpServer.Shutdown(s.ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif s.listener != nil {\n\t\terr = s.listener.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Server) GetCtx() context.Context {\n\treturn s.ctx\n}\n"
  },
  {
    "path": "windows/README.md",
    "content": "# Windows Files\n\nThis directory contains all Windows-specific files for S-UI.\n\n## Available Files:\n\n- **s-ui-windows.xml**: Windows Service configuration\n- **install-windows.bat**: Installation script\n- **s-ui-windows.bat**: Control panel\n- **uninstall-windows.bat**: Uninstallation script\n- **build-windows.bat**: Simple build script for CMD\n- **build-windows.ps1**: Advanced build script for PowerShell\n\n## Usage:\n\nTo install S-UI on Windows:\n1. Run `install-windows.bat` as Administrator\n2. Follow the installation wizard\n3. Use `s-ui-windows.bat` for management\n\nTo build from source:\n- With CMD: `build-windows.bat`\n- With PowerShell: `.\\build-windows.ps1`\n"
  },
  {
    "path": "windows/build-windows.bat",
    "content": "@echo off\nsetlocal enabledelayedexpansion\n\necho Building S-UI for Windows...\n\ncd /d \"%~dp0\"\n\nREM Check if Go is installed\ngo version >nul 2>&1\nif errorlevel 1 (\n    echo Error: Go is not installed or not in PATH\n    echo Please install Go from https://golang.org/dl/\n    pause\n    exit /b 1\n)\n\nREM Check if Node.js is installed\nnode --version >nul 2>&1\nif errorlevel 1 (\n    echo Error: Node.js is not installed or not in PATH\n    echo Please install Node.js from https://nodejs.org/\n    pause\n    exit /b 1\n)\n\necho Building frontend...\ncd frontend\ncall npm install\nif errorlevel 1 (\n    echo Error: Failed to install frontend dependencies\n    pause\n    exit /b 1\n)\n\ncall npm run build\nif errorlevel 1 (\n    echo Error: Failed to build frontend\n    pause\n    exit /b 1\n)\n\ncd ..\n\necho Creating web/html directory...\nif not exist \"web\\html\" mkdir \"web\\html\"\n\necho Copying frontend build files...\nxcopy \"frontend\\dist\\*\" \"web\\html\\\" /E /Y /Q\n\necho Building backend...\nset CGO_ENABLED=1\nset GOOS=windows\nset GOARCH=amd64\n\nREM Try to build with CGO first\ngo build -ldflags \"-w -s\" -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor\" -o sui.exe main.go\nif errorlevel 1 (\n    echo Warning: CGO build failed, trying without CGO...\n    set CGO_ENABLED=0\n    go build -ldflags \"-w -s\" -tags \"with_quic,with_grpc,with_utls,with_acme,with_gvisor\" -o sui.exe main.go\n    if errorlevel 1 (\n        echo Error: Failed to build backend\n        pause\n        exit /b 1\n    )\n    echo Built without CGO (some features may be limited)\n) else (\n    echo Built with CGO\n)\n\necho Build completed successfully!\necho Output: sui.exe\npause\n"
  },
  {
    "path": "windows/build-windows.ps1",
    "content": "# PowerShell script for building S-UI on Windows\nparam(\n    [string]$Architecture = \"amd64\",\n    [switch]$NoCGO,\n    [switch]$Help\n)\n\nif ($Help) {\n    Write-Host \"Usage: .\\build-windows.ps1 [-Architecture <arch>] [-NoCGO] [-Help]\"\n    Write-Host \"Architectures: amd64, 386, arm64\"\n    Write-Host \"Examples:\"\n    Write-Host \"  .\\build-windows.ps1                    # Build for amd64 with CGO\"\n    Write-Host \"  .\\build-windows.ps1 -Architecture 386 # Build for 32-bit Windows\"\n    Write-Host \"  .\\build-windows.ps1 -NoCGO            # Build without CGO\"\n    exit 0\n}\n\nWrite-Host \"Building S-UI for Windows ($Architecture)...\" -ForegroundColor Green\n\n# Check if Go is installed\ntry {\n    $goVersion = go version 2>$null\n    if ($LASTEXITCODE -ne 0) {\n        throw \"Go not found\"\n    }\n    Write-Host \"Go version: $goVersion\" -ForegroundColor Green\n} catch {\n    Write-Host \"Error: Go is not installed or not in PATH\" -ForegroundColor Red\n    Write-Host \"Please install Go from https://golang.org/dl/\" -ForegroundColor Yellow\n    Read-Host \"Press Enter to exit\"\n    exit 1\n}\n\n# Check if Node.js is installed\ntry {\n    $nodeVersion = node --version 2>$null\n    if ($LASTEXITCODE -ne 0) {\n        throw \"Node.js not found\"\n    }\n    Write-Host \"Node.js version: $nodeVersion\" -ForegroundColor Green\n} catch {\n    Write-Host \"Error: Node.js is not installed or not in PATH\" -ForegroundColor Red\n    Write-Host \"Please install Node.js from https://nodejs.org/\" -ForegroundColor Yellow\n    Read-Host \"Press Enter to exit\"\n    exit 1\n}\n\n# Build frontend\nWrite-Host \"Building frontend...\" -ForegroundColor Yellow\nPush-Location frontend\n\ntry {\n    Write-Host \"Installing dependencies...\" -ForegroundColor Cyan\n    npm install\n    if ($LASTEXITCODE -ne 0) {\n        throw \"Failed to install frontend dependencies\"\n    }\n\n    Write-Host \"Building frontend...\" -ForegroundColor Cyan\n    npm run build\n    if ($LASTEXITCODE -ne 0) {\n        throw \"Failed to build frontend\"\n    }\n} catch {\n    Write-Host \"Error: $_\" -ForegroundColor Red\n    Pop-Location\n    Read-Host \"Press Enter to exit\"\n    exit 1\n}\n\nPop-Location\n\n# Create web/html directory\nWrite-Host \"Creating web/html directory...\" -ForegroundColor Yellow\nif (!(Test-Path \"web\\html\")) {\n    New-Item -ItemType Directory -Path \"web\\html\" -Force | Out-Null\n}\n\n# Copy frontend build files\nWrite-Host \"Copying frontend build files...\" -ForegroundColor Yellow\nCopy-Item \"frontend\\dist\\*\" \"web\\html\\\" -Recurse -Force\n\n# Build backend\nWrite-Host \"Building backend...\" -ForegroundColor Yellow\n\n# Set environment variables\n$env:GOOS = \"windows\"\n$env:GOARCH = $Architecture\n\nif ($NoCGO) {\n    $env:CGO_ENABLED = \"0\"\n    Write-Host \"Building without CGO...\" -ForegroundColor Yellow\n} else {\n    $env:CGO_ENABLED = \"1\"\n    Write-Host \"Building with CGO...\" -ForegroundColor Yellow\n}\n\n# Build command\n$buildCmd = \"go build -ldflags `\"-w -s`\" -tags `\"with_quic,with_grpc,with_utls,with_acme,with_gvisor`\" -o sui.exe main.go\"\n\ntry {\n    Invoke-Expression $buildCmd\n    if ($LASTEXITCODE -ne 0) {\n        if (!$NoCGO) {\n            Write-Host \"CGO build failed, trying without CGO...\" -ForegroundColor Yellow\n            $env:CGO_ENABLED = \"0\"\n            Invoke-Expression $buildCmd\n            if ($LASTEXITCODE -ne 0) {\n                throw \"Failed to build backend even without CGO\"\n            }\n            Write-Host \"Built without CGO (some features may be limited)\" -ForegroundColor Yellow\n        } else {\n            throw \"Failed to build backend\"\n        }\n    } else {\n        if ($env:CGO_ENABLED -eq \"1\") {\n            Write-Host \"Built successfully with CGO\" -ForegroundColor Green\n        } else {\n            Write-Host \"Built successfully without CGO\" -ForegroundColor Green\n        }\n    }\n} catch {\n    Write-Host \"Error: $_\" -ForegroundColor Red\n    Read-Host \"Press Enter to exit\"\n    exit 1\n}\n\nWrite-Host \"Build completed successfully!\" -ForegroundColor Green\nWrite-Host \"Output: sui.exe\" -ForegroundColor Green\n\n# Show file info\nif (Test-Path \"sui.exe\") {\n    $fileInfo = Get-Item \"sui.exe\"\n    Write-Host \"File size: $([math]::Round($fileInfo.Length / 1MB, 2)) MB\" -ForegroundColor Cyan\n    Write-Host \"Created: $($fileInfo.CreationTime)\" -ForegroundColor Cyan\n}\n\nRead-Host \"Press Enter to exit\"\n"
  },
  {
    "path": "windows/install-windows.bat",
    "content": "@echo off\nsetlocal enabledelayedexpansion\n\necho ========================================\necho S-UI Windows Installer\necho ========================================\n\nREM Check if running as Administrator\nnet session >nul 2>&1\nif %errorLevel% neq 0 (\n    echo Error: This script must be run as Administrator\n    echo Right-click on this file and select \"Run as administrator\"\n    pause\n    exit /b 1\n)\n\ncd /d \"%~dp0\"\nREM Set installation directory\nset \"INSTALL_DIR=C:\\Program Files\\s-ui\"\nset \"SERVICE_NAME=s-ui\"\n\necho Installing S-UI to: %INSTALL_DIR%\n\nREM Create installation directory\nif not exist \"%INSTALL_DIR%\" mkdir \"%INSTALL_DIR%\"\nif not exist \"%INSTALL_DIR%\\db\" mkdir \"%INSTALL_DIR%\\db\"\nif not exist \"%INSTALL_DIR%\\logs\" mkdir \"%INSTALL_DIR%\\logs\"\nif not exist \"%INSTALL_DIR%\\cert\" mkdir \"%INSTALL_DIR%\\cert\"\n\nREM Copy files\necho Copying files...\ncopy \"sui.exe\" \"%INSTALL_DIR%\\\" >nul\ncopy \"s-ui-windows.xml\" \"%INSTALL_DIR%\\\" >nul\ncopy \"s-ui-windows.bat\" \"%INSTALL_DIR%\\\" >nul\n\nREM Check if WinSW is available\nset \"WINSW_PATH=%INSTALL_DIR%\\winsw.exe\"\nif not exist \"%WINSW_PATH%\" (\n    echo Downloading WinSW...\n    powershell -Command \"& {Invoke-WebRequest -Uri 'https://github.com/winsw/winsw/releases/download/v2.12.0/WinSW-x64.exe' -OutFile '%WINSW_PATH%'}\"\n    if exist \"%WINSW_PATH%\" (\n        echo WinSW downloaded successfully\n    ) else (\n        echo Warning: Failed to download WinSW. Service installation will be skipped.\n        echo You can manually download WinSW from: https://github.com/winsw/winsw/releases\n    )\n)\n\nREM Install Windows Service\nif exist \"%WINSW_PATH%\" (\n    echo Installing Windows Service...\n    cd /d \"%INSTALL_DIR%\"\n    copy \"winsw.exe\" \"s-ui-service.exe\" >nul\n    copy \"s-ui-windows.xml\" \"s-ui-service.xml\" >nul\n        \n    REM Install service\n    s-ui-service.exe install\n    if %errorLevel% equ 0 (\n        echo Service installed successfully\n    ) else (\n        echo Warning: Failed to install service. You can install it manually later.\n    )\n)\n\nREM Run migration\necho Running database migration...\ncd /d \"%INSTALL_DIR%\"\nsui.exe migrate\nif %errorLevel% equ 0 (\n    echo Migration completed successfully\n) else (\n    echo Warning: Migration failed or database is new\n)\n\nREM Get network configuration\necho.\necho ========================================\necho Network Configuration\necho ========================================\n\nREM Get local IP addresses\necho Available IP addresses:\nfor /f \"tokens=2 delims=:\" %%i in ('ipconfig ^| findstr /i \"IPv4\"') do (\n    echo   %%i\n)\n\nREM Get panel configuration\necho.\nset /p panel_port=\"Enter panel port (default: 2095): \"\nif \"%panel_port%\"==\"\" set \"panel_port=2095\"\n\nset /p panel_path=\"Enter panel path (default: /app/): \"\nif \"%panel_path%\"==\"\" set \"panel_path=/app/\"\n\nset /p sub_port=\"Enter subscription port (default: 2096): \"\nif \"%sub_port%\"==\"\" set \"sub_port=2096\"\n\nset /p sub_path=\"Enter subscription path (default: /sub/): \"\nif \"%sub_path%\"==\"\" set \"sub_path=/sub/\"\n\nREM Apply settings\necho.\necho Applying settings...\ncd /d \"%INSTALL_DIR%\"\nsui.exe setting -port %panel_port% -path \"%panel_path%\" -subPort %sub_port% -subPath \"%sub_path%\"\n\nREM Get admin credentials\necho.\necho ========================================\necho Admin Configuration\necho ========================================\n\nset /p admin_username=\"Enter admin username (default: admin): \"\nif \"%admin_username%\"==\"\" set \"admin_username=admin\"\n\nset /p admin_password=\"Enter admin password: \"\nif \"%admin_password%\"==\"\" (\n    echo Error: Password cannot be empty\n    pause\n    exit /b 1\n)\n\nREM Set admin credentials\necho Setting admin credentials...\nsui.exe admin -username \"%admin_username%\" -password \"%admin_password%\"\n\nREM Start service\necho Starting S-UI service...\nnet start %SERVICE_NAME%\nif %errorLevel% equ 0 (\n    echo Service started successfully\n) else (\n    echo Warning: Failed to start service. You can start it manually later.\n)\n\nREM Create desktop shortcut\necho Creating desktop shortcut...\nset \"DESKTOP=%USERPROFILE%\\Desktop\"\nif exist \"%DESKTOP%\" (\n    powershell -Command \"& {$WshShell = New-Object -comObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%DESKTOP%\\S-UI.lnk'); $Shortcut.TargetPath = '%INSTALL_DIR%\\s-ui-windows.bat'; $Shortcut.WorkingDirectory = '%INSTALL_DIR%'; $Shortcut.Description = 'S-UI Control Panel'; $Shortcut.Save()}\"\n    echo Desktop shortcut created\n)\n\nREM Create Start Menu shortcut\necho Creating Start Menu shortcut...\nset \"START_MENU=%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\"\nif exist \"%START_MENU%\" (\n    if not exist \"%START_MENU%\\S-UI\" mkdir \"%START_MENU%\\S-UI\"\n    powershell -Command \"& {$WshShell = New-Object -comObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%START_MENU%\\S-UI\\S-UI Control Panel.lnk'); $Shortcut.TargetPath = '%INSTALL_DIR%\\s-ui-windows.bat'; $Shortcut.WorkingDirectory = '%INSTALL_DIR%'; $Shortcut.Description = 'S-UI Control Panel'; $Shortcut.Save()}\"\n    echo Start Menu shortcut created\n)\n\nREM Set permissions\necho Setting permissions...\nicacls \"%INSTALL_DIR%\" /grant \"Users:(OI)(CI)RX\" /T >nul\nicacls \"%INSTALL_DIR%\\db\" /grant \"Users:(OI)(CI)F\" /T >nul\nicacls \"%INSTALL_DIR%\\logs\" /grant \"Users:(OI)(CI)F\" /T >nul\n\nREM Create environment variable\necho Setting environment variable...\nsetx SUI_HOME \"%INSTALL_DIR%\" /M >nul\n\nREM Show final configuration\necho.\necho ========================================\necho Installation completed successfully!\necho ========================================\necho.\necho S-UI has been installed to: %INSTALL_DIR%\necho.\necho Configuration:\necho   Panel Port: %panel_port%\necho   Panel Path: %panel_path%\necho   Subscription Port: %sub_port%\necho   Subscription Path: %sub_path%\necho   Admin Username: %admin_username%\necho.\necho Access URLs:\nfor /f \"tokens=2 delims=:\" %%i in ('ipconfig ^| findstr /i \"IPv4\"') do (\n    set \"ip=%%i\"\n    set \"ip=!ip: =!\"\n    echo   Panel: http://!ip!:%panel_port%%panel_path%\n    echo   Subscription: http://!ip!:%sub_port%%sub_path%\n)\necho.\necho Service name: %SERVICE_NAME%\necho.\necho Useful commands:\necho   net start %SERVICE_NAME%    - Start the service\necho   net stop %SERVICE_NAME%     - Stop the service\necho   sc query %SERVICE_NAME%     - Check service status\necho.\necho You can also use the desktop shortcut or Start Menu item.\necho.\npause\n"
  },
  {
    "path": "windows/s-ui-windows.bat",
    "content": "@echo off\nsetlocal enabledelayedexpansion\n\nREM S-UI Windows Control Script\nREM This script provides a menu-driven interface for managing S-UI on Windows\n\ncd /d \"%~dp0\"\nset \"SERVICE_NAME=s-ui\"\nset \"INSTALL_DIR=%SUI_HOME%\"\nif \"%INSTALL_DIR%\"==\"\" set \"INSTALL_DIR=C:\\Program Files\\s-ui\"\n\n:menu\ncls\necho ========================================\necho S-UI Windows Control Panel\necho ========================================\necho.\necho Current directory: %INSTALL_DIR%\necho.\necho 1. Start S-UI Service\necho 2. Stop S-UI Service\necho 3. Restart S-UI Service\necho 4. Check Service Status\necho 5. View Service Logs\necho 6. Open Panel in Browser\necho 7. Run S-UI Manually\necho 8. Install/Uninstall Service\necho 9. Open Installation Directory\necho 10. Show Configuration\necho 11. Show Access URLs\necho 0. Exit\necho.\necho ========================================\n\nset /p choice=\"Please select an option [0-11]: \"\n\nif \"%choice%\"==\"1\" goto start_service\nif \"%choice%\"==\"2\" goto stop_service\nif \"%choice%\"==\"3\" goto restart_service\nif \"%choice%\"==\"4\" goto check_status\nif \"%choice%\"==\"5\" goto view_logs\nif \"%choice%\"==\"6\" goto open_panel\nif \"%choice%\"==\"7\" goto run_manual\nif \"%choice%\"==\"8\" goto service_management\nif \"%choice%\"==\"9\" goto open_directory\nif \"%choice%\"==\"10\" goto show_config\nif \"%choice%\"==\"11\" goto show_urls\nif \"%choice%\"==\"0\" goto exit\ngoto invalid_choice\n\n:start_service\necho Starting S-UI service...\nnet start %SERVICE_NAME%\nif %errorLevel% equ 0 (\n    echo Service started successfully!\n) else (\n    echo Failed to start service. Error code: %errorLevel%\n)\npause\ngoto menu\n\n:stop_service\necho Stopping S-UI service...\nnet stop %SERVICE_NAME%\nif %errorLevel% equ 0 (\n    echo Service stopped successfully!\n) else (\n    echo Failed to stop service. Error code: %errorLevel%\n)\npause\ngoto menu\n\n:restart_service\necho Restarting S-UI service...\nnet stop %SERVICE_NAME% >nul 2>&1\ntimeout /t 2 /nobreak >nul\nnet start %SERVICE_NAME%\nif %errorLevel% equ 0 (\n    echo Service restarted successfully!\n) else (\n    echo Failed to restart service. Error code: %errorLevel%\n)\npause\ngoto menu\n\n:check_status\necho Checking S-UI service status...\nsc query %SERVICE_NAME%\necho.\necho Service status details:\nfor /f \"tokens=3 delims=: \" %%i in ('sc query %SERVICE_NAME% ^| find \"STATE\"') do (\n    echo Current state: %%i\n)\npause\ngoto menu\n\n:view_logs\necho Opening S-UI logs...\nif exist \"%INSTALL_DIR%\\logs\" (\n    start \"\" \"%INSTALL_DIR%\\logs\"\n) else (\n    echo Logs directory not found: %INSTALL_DIR%\\logs\n)\npause\ngoto menu\n\n:open_panel\necho Opening S-UI panel in browser...\nstart http://localhost:2095\necho Panel opened in default browser.\npause\ngoto menu\n\n:run_manual\necho Running S-UI manually...\nif exist \"%INSTALL_DIR%\\sui.exe\" (\n    cd /d \"%INSTALL_DIR%\"\n    echo Starting S-UI in current window...\n    echo Press Ctrl+C to stop\n    echo.\n    sui.exe\n) else (\n    echo S-UI executable not found: %INSTALL_DIR%\\sui.exe\n    echo Please run the installer first.\n)\npause\ngoto menu\n\n:service_management\ncls\necho ========================================\necho Service Management\necho ========================================\necho.\necho 1. Install Windows Service\necho 2. Uninstall Windows Service\necho 3. Back to Main Menu\necho.\nset /p service_choice=\"Select option [1-3]: \"\n\nif \"%service_choice%\"==\"1\" goto install_service\nif \"%service_choice%\"==\"2\" goto uninstall_service\nif \"%service_choice%\"==\"3\" goto menu\ngoto invalid_choice\n\n:install_service\necho Installing Windows Service...\nif exist \"%INSTALL_DIR%\\s-ui-service.exe\" (\n    cd /d \"%INSTALL_DIR%\"\n    s-ui-service.exe install\n    if %errorLevel% equ 0 (\n        echo Service installed successfully!\n        echo Starting service...\n        net start %SERVICE_NAME%\n    ) else (\n        echo Failed to install service. Error code: %errorLevel%\n    )\n) else (\n    echo Service wrapper not found. Please run the installer first.\n)\npause\ngoto service_management\n\n:uninstall_service\necho Uninstalling Windows Service...\nif exist \"%INSTALL_DIR%\\s-ui-service.exe\" (\n    cd /d \"%INSTALL_DIR%\"\n    net stop %SERVICE_NAME% >nul 2>&1\n    s-ui-service.exe uninstall\n    if %errorLevel% equ 0 (\n        echo Service uninstalled successfully!\n    ) else (\n        echo Failed to uninstall service. Error code: %errorLevel%\n    )\n) else (\n    echo Service wrapper not found.\n)\npause\ngoto service_management\n\n:open_directory\necho Opening installation directory...\nif exist \"%INSTALL_DIR%\" (\n    start \"\" \"%INSTALL_DIR%\"\n) else (\n    echo Installation directory not found: %INSTALL_DIR%\n)\npause\ngoto menu\n\n:show_config\necho.\necho ========================================\necho S-UI Configuration\necho ========================================\nif exist \"%INSTALL_DIR%\\sui.exe\" (\n    cd /d \"%INSTALL_DIR%\"\n    echo Current settings:\n    sui.exe setting -show\n    echo.\n    echo Admin credentials:\n    sui.exe admin -show\n) else (\n    echo S-UI executable not found. Please run the installer first.\n)\npause\ngoto menu\n\n:show_urls\necho.\necho ========================================\necho Access URLs\necho ========================================\necho.\necho Local access:\necho   Panel: http://localhost:2095\necho   Subscription: http://localhost:2096\necho.\necho Network access:\nfor /f \"tokens=2 delims=:\" %%i in ('ipconfig ^| findstr /i \"IPv4\"') do (\n    set \"ip=%%i\"\n    set \"ip=!ip: =!\"\n    echo   Panel: http://!ip!:2095\n    echo   Subscription: http://!ip!:2096\n)\necho.\npause\ngoto menu\n\n:invalid_choice\necho Invalid choice. Please select a valid option.\npause\ngoto menu\n\n:exit\necho Thank you for using S-UI Windows Control Panel!\nexit /b 0\n"
  },
  {
    "path": "windows/s-ui-windows.xml",
    "content": "<?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 a proxy panel for managing proxy services</description>\n  <executable>%BASE%\\sui.exe</executable>\n  <arguments></arguments>\n  <logmode>rotate</logmode>\n  <logpath>%BASE%\\logs</logpath>\n  <log size=\"10 m\" />\n  <log keep=\"10\" />\n  <workingdirectory>%BASE%</workingdirectory>\n  <env name=\"SUI_DB_FOLDER\" value=\"db\" />\n  <env name=\"SUI_DEBUG\" value=\"false\" />\n  <onfailure action=\"restart\" delay=\"10 sec\" />\n  <onfailure action=\"restart\" delay=\"20 sec\" />\n  <onfailure action=\"none\" />\n  <resetfailure>1 hour</resetfailure>\n  <startmode>Automatic</startmode>\n  <depend>tcpip</depend>\n  <depend>netman</depend>\n</service>\n"
  },
  {
    "path": "windows/uninstall-windows.bat",
    "content": "@echo off\nsetlocal enabledelayedexpansion\n\necho ========================================\necho S-UI Windows Uninstaller\necho ========================================\n\nREM Check if running as Administrator\nnet session >nul 2>&1\nif %errorLevel% neq 0 (\n    echo Error: This script must be run as Administrator\n    echo Right-click on this file and select \"Run as administrator\"\n    pause\n    exit /b 1\n)\n\nREM Set installation directory\nset \"INSTALL_DIR=C:\\Program Files\\s-ui\"\nset \"SERVICE_NAME=s-ui\"\n\necho Uninstalling S-UI from: %INSTALL_DIR%\n\nREM Stop and remove Windows Service\nif exist \"%INSTALL_DIR%\\s-ui-service.exe\" (\n    echo Stopping and removing Windows Service...\n    net stop %SERVICE_NAME% >nul 2>&1\n    cd /d \"%INSTALL_DIR%\"\n    s-ui-service.exe uninstall >nul 2>&1\n    if %errorLevel% equ 0 (\n        echo Service removed successfully\n    ) else (\n        echo Warning: Failed to remove service or service was not installed\n    )\n)\n\nREM Remove desktop shortcut\necho Removing desktop shortcut...\nset \"DESKTOP=%USERPROFILE%\\Desktop\"\nif exist \"%DESKTOP%\\S-UI.lnk\" (\n    del \"%DESKTOP%\\S-UI.lnk\" >nul 2>&1\n    echo Desktop shortcut removed\n)\n\nREM Remove Start Menu shortcut\necho Removing Start Menu shortcut...\nset \"START_MENU=%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\S-UI\"\nif exist \"%START_MENU%\" (\n    rmdir /s /q \"%START_MENU%\" >nul 2>&1\n    echo Start Menu shortcut removed\n)\n\nREM Remove environment variable\necho Removing environment variable...\nreg delete \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v SUI_HOME /f >nul 2>&1\n\nREM Ask user if they want to keep data\necho.\nset /p keep_data=\"Do you want to keep your data (database, logs, certificates)? [y/n]: \"\nif /i \"%keep_data%\"==\"y\" (\n    echo Keeping data files...\n    REM Remove only executable and service files\n    if exist \"%INSTALL_DIR%\\sui.exe\" del \"%INSTALL_DIR%\\sui.exe\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\s-ui-service.exe\" del \"%INSTALL_DIR%\\s-ui-service.exe\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\s-ui-service.xml\" del \"%INSTALL_DIR%\\s-ui-service.xml\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\winsw.exe\" del \"%INSTALL_DIR%\\winsw.exe\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\*.bat\" del \"%INSTALL_DIR%\\*.bat\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\*.xml\" del \"%INSTALL_DIR%\\*.xml\" >nul 2>&1\n    if exist \"%INSTALL_DIR%\\*.md\" del \"%INSTALL_DIR%\\*.md\" >nul 2>&1\n    echo Data files preserved in: %INSTALL_DIR%\n) else (\n    echo Removing all files...\n    REM Remove entire installation directory\n    if exist \"%INSTALL_DIR%\" (\n        rmdir /s /q \"%INSTALL_DIR%\" >nul 2>&1\n        if exist \"%INSTALL_DIR%\" (\n            echo Warning: Some files could not be removed. Please manually delete: %INSTALL_DIR%\n        ) else (\n            echo All files removed successfully\n        )\n    )\n)\n\nREM Remove firewall rules\necho Removing firewall rules...\nnetsh advfirewall firewall delete rule name=\"S-UI Panel\" >nul 2>&1\nnetsh advfirewall firewall delete rule name=\"S-UI Subscription\" >nul 2>&1\n\necho.\necho ========================================\necho Uninstallation completed!\necho ========================================\necho.\necho S-UI has been uninstalled from your system.\necho.\nif /i \"%keep_data%\"==\"y\" (\n    echo Your data has been preserved in: %INSTALL_DIR%\n    echo You can safely delete this directory if you no longer need the data.\n)\necho.\necho Thank you for using S-UI!\necho.\npause\n"
  }
]