Full Code of rustdesk/rustdesk-server for AI

master 815c728837b8 cached
87 files
250.5 KB
62.4k tokens
166 symbols
1 requests
Download .txt
Showing preview only (271K chars total). Download the full file or copy to clipboard to get everything.
Repository: rustdesk/rustdesk-server
Branch: master
Commit: 815c728837b8
Files: 87
Total size: 250.5 KB

Directory structure:
gitextract_n71cs4xt/

├── .cargo/
│   └── config.toml
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── dependabot.yml
│   └── workflows/
│       └── build.yaml
├── .gitignore
├── .gitmodules
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
├── debian/
│   ├── README.source
│   ├── changelog
│   ├── compat
│   ├── control.tpl
│   ├── copyright
│   ├── rules
│   ├── rustdesk-server-hbbr.install
│   ├── rustdesk-server-hbbr.postinst
│   ├── rustdesk-server-hbbr.postrm
│   ├── rustdesk-server-hbbr.prerm
│   ├── rustdesk-server-hbbs.install
│   ├── rustdesk-server-hbbs.postinst
│   ├── rustdesk-server-hbbs.postrm
│   ├── rustdesk-server-hbbs.prerm
│   ├── rustdesk-server-utils.install
│   └── source/
│       └── format
├── docker/
│   ├── Dockerfile
│   ├── healthcheck.sh
│   └── rootfs/
│       ├── etc/
│       │   └── s6-overlay/
│       │       └── s6-rc.d/
│       │           ├── hbbr/
│       │           │   ├── dependencies
│       │           │   ├── run
│       │           │   └── type
│       │           ├── hbbs/
│       │           │   ├── dependencies
│       │           │   ├── run
│       │           │   └── type
│       │           ├── key-secret/
│       │           │   ├── type
│       │           │   ├── up
│       │           │   └── up.real
│       │           └── user/
│       │               └── contents.d/
│       │                   ├── hbbr
│       │                   ├── hbbs
│       │                   └── key-secret
│       └── usr/
│           └── bin/
│               └── healthcheck.sh
├── docker-classic/
│   └── Dockerfile
├── docker-compose.yml
├── kubernetes/
│   └── example.yaml
├── rcd/
│   ├── rustdesk-hbbr
│   └── rustdesk-hbbs
├── src/
│   ├── common.rs
│   ├── database.rs
│   ├── hbbr.rs
│   ├── lib.rs
│   ├── main.rs
│   ├── mod.rs
│   ├── peer.rs
│   ├── relay_server.rs
│   ├── rendezvous_server.rs
│   └── utils.rs
├── systemd/
│   ├── rustdesk-hbbr.service
│   └── rustdesk-hbbs.service
└── ui/
    ├── .cargo/
    │   └── config.toml
    ├── .gitignore
    ├── Cargo.toml
    ├── build.rs
    ├── html/
    │   ├── .gitignore
    │   ├── index.html
    │   ├── main.js
    │   ├── package.json
    │   ├── style.css
    │   └── vite.config.js
    ├── icons/
    │   └── icon.icns
    ├── setup/
    │   └── service/
    │       └── run.cmd
    ├── setup.nsi
    ├── src/
    │   ├── adapter/
    │   │   ├── mod.rs
    │   │   ├── service/
    │   │   │   ├── mod.rs
    │   │   │   └── windows.rs
    │   │   └── view/
    │   │       ├── desktop.rs
    │   │       └── mod.rs
    │   ├── lib.rs
    │   ├── main.rs
    │   └── usecase/
    │       ├── mod.rs
    │       ├── presenter.rs
    │       ├── service.rs
    │       ├── view.rs
    │       └── watcher.rs
    └── tauri.conf.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .cargo/config.toml
================================================
[target.x86_64-pc-windows-msvc]
rustflags = ["-Ctarget-feature=+crt-static"]
[target.i686-pc-windows-msvc]
rustflags = ["-Ctarget-feature=+crt-static"]
[target.'cfg(target_os="macos")']
rustflags = [
    "-C", "link-args=-sectcreate __CGPreLoginApp __cgpreloginapp /dev/null",
]

================================================
FILE: .gitattributes
================================================
* text=auto


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug'
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**Describe the environment**
 - Install environment: docker, docker swarm, podman, kubernetes, or package
 - If available, the `docker-compose.yaml` file
 - If package, we need the distribution and release: Ubuntu 22.04, Debian 11, ...
 - Or if you're running the plain binary, how you're running it
 - In any case, you have to specify the version in use

**How to Reproduce the bug**
Steps to reproduce the behavior:
1. Given the previously described environment
2. Do this and that
3. I get this error

**Expected behavior**
This should happen instead.

**Additional context**
Add any other context about the problem here.

**Notes**
 - Please write in english only. If you provide some images in different languages, you're required to write a translation in english.
 - In any case, **NEVER** put here the content if your `id_ed25519` file
 

================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'enhancement'
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is.

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context about the feature request here.

**Notes**
 - Please write in english only. If you provide some images in different languages, you're required to write a translation in english.
 - In any case, **NEVER** put here the content if your `id_ed25519` file
 

================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
  - package-ecosystem: "gitsubmodule"
    directory: "/"
    target-branch: "master"
    schedule:
      interval: "daily"
    commit-message:
      prefix: "Git submodule"
    labels:
      - "dependencies"


================================================
FILE: .github/workflows/build.yaml
================================================
name: build

# ------------- NOTE
# please setup some secrets before running this workflow:
# DOCKER_IMAGE should be the target image name on docker hub (e.g. "rustdesk/rustdesk-server-s6" )
# DOCKER_IMAGE_CLASSIC should be the target image name on docker hub for the old build (e.g. "rustdesk/rustdesk-server" )
# DOCKER_HUB_USERNAME is the username you normally use to login at https://hub.docker.com/
# DOCKER_HUB_PASSWORD is a token you should create under "account settings / security" with read/write access

permissions:
  contents: read
  packages: write

on:
  workflow_dispatch:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'
      - '[0-9]+.[0-9]+.[0-9]+'
      - 'v[0-9]+.[0-9]+.[0-9]+-[0-9]+'
      - '[0-9]+.[0-9]+.[0-9]+-[0-9]+'

env:
  CARGO_TERM_COLOR: always
  LATEST_TAG: latest
  GHCR_IMAGE: ghcr.io/rustdesk/rustdesk-server-s6
  GHCR_IMAGE_CLASSIC: ghcr.io/rustdesk/rustdesk-server
  
jobs:

  # binary build
  build:

    name: Build - ${{ matrix.job.name }}
    runs-on: ubuntu-22.04
    strategy:
      fail-fast: false
      matrix:
        job:
          - { name: "amd64",   target: "x86_64-unknown-linux-musl" }
          - { name: "arm64v8", target: "aarch64-unknown-linux-musl" }
          - { name: "armv7",   target: "armv7-unknown-linux-musleabihf" }
          - { name: "i386",    target: "i686-unknown-linux-musl" }
          #- { name: "amd64fb",    target: "x86_64-unknown-freebsd" }

    steps:
      
      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Install toolchain
        uses: actions-rs/toolchain@v1
        with:
          toolchain: "1.90"
          override: true
          default: true
          components: rustfmt
          profile: minimal
          target: ${{ matrix.job.target }}

      - name: Build
        uses: actions-rs/cargo@v1
        with:
          command: build
          args: --release --all-features --target=${{ matrix.job.target }}
          use-cross: true  

      - name: Exec chmod
        run: chmod -v a+x target/${{ matrix.job.target }}/release/*

      - name: Publish Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: binaries-linux-${{ matrix.job.name }}
          path: |
            target/${{ matrix.job.target }}/release/hbbr
            target/${{ matrix.job.target }}/release/hbbs
            target/${{ matrix.job.target }}/release/rustdesk-utils
          if-no-files-found: error

  build-win:
    name: Build - windows
    runs-on: windows-2022

    steps:
      
      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Install toolchain
        uses: actions-rs/toolchain@v1
        with:
          toolchain: "1.90"
          override: true
          default: true
          components: rustfmt
          profile: minimal
          target: x86_64-pc-windows-msvc

      - name: Build
        uses: actions-rs/cargo@v1
        with:
          command: build
          args: --release --all-features --target=x86_64-pc-windows-msvc
          use-cross: true

      - name: Install NSIS
        run: |
          iwr -useb get.scoop.sh -outfile 'install.ps1'
          .\install.ps1 -RunAsAdmin
          scoop update
          scoop bucket add extras
          scoop install nsis

      - name: Install Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16

      - name: Sign exe files
        uses: GermanBluefox/code-sign-action@v7
        if: false
        with:
          certificate: '${{ secrets.WINDOWS_PFX_BASE64 }}'
          password: '${{ secrets.WINDOWS_PFX_PASSWORD }}'
          certificatesha1: '${{ secrets.WINDOWS_PFX_SHA1_THUMBPRINT }}'
          folder: 'target\x86_64-pc-windows-msvc\release'
          recursive: false

      - name: Build UI browser file
        run: |
          npm i
          npm run build
        working-directory: ./ui/html

      - name: Build UI setup file
        run: |
          rustup default nightly
          cargo build --release
          xcopy /y ..\target\x86_64-pc-windows-msvc\release\*.exe setup\bin\
          xcopy /y target\release\*.exe setup\
          mkdir setup\logs
          makensis /V1 setup.nsi
          mkdir SignOutput
          mv RustDeskServer.Setup.exe SignOutput\
          mv ..\target\x86_64-pc-windows-msvc\release\*.exe SignOutput\
        working-directory: ./ui

      - name: Sign UI setup file 
        uses: GermanBluefox/code-sign-action@v7
        if: false
        with:
          certificate: '${{ secrets.WINDOWS_PFX_BASE64 }}'
          password: '${{ secrets.WINDOWS_PFX_PASSWORD }}'
          certificatesha1: '${{ secrets.WINDOWS_PFX_SHA1_THUMBPRINT }}'
          folder: './ui/SignOutput'
          recursive: false

      - name: Publish Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: binaries-windows-x86_64
          path: |
            ui\SignOutput\hbbr.exe
            ui\SignOutput\hbbs.exe
            ui\SignOutput\rustdesk-utils.exe
            ui\SignOutput\RustDeskServer.Setup.exe
          if-no-files-found: error

  # github (draft) release with all binaries
  release:

    name: Github release
    needs: 
      - build
      - build-win
    runs-on: ubuntu-22.04
    strategy:
      fail-fast: false
      matrix:
        job:
          - { os: "linux", name: "amd64", suffix: "" }
          - { os: "linux", name: "arm64v8", suffix: "" }
          - { os: "linux", name: "armv7", suffix: "" }
          - { os: "linux", name: "i386", suffix: "" }
          #- { os: "linux", name: "amd64fb", suffix: "" }
          - { os: "windows", name: "x86_64", suffix: "-unsigned" }
          
    steps:

      - name: Download binaries (${{ matrix.job.os }} - ${{ matrix.job.name }})
        uses: actions/download-artifact@v4
        with:
          name: binaries-${{ matrix.job.os }}-${{ matrix.job.name }}
          path: ${{ matrix.job.name }}

      - name: Exec chmod
        run: chmod -v a+x ${{ matrix.job.name }}/*

      - name: Pack files (${{ matrix.job.os }} - ${{ matrix.job.name }})
        run: |
          sudo apt update
          DEBIAN_FRONTEND=noninteractive sudo apt install -y zip
          zip ${{ matrix.job.name }}/rustdesk-server-${{ matrix.job.os }}-${{ matrix.job.name }}${{ matrix.job.suffix }}.zip ${{ matrix.job.name }}/*

      - name: Create Release (${{ matrix.job.os }} - (${{ matrix.job.name }})
        uses: softprops/action-gh-release@v1
        with:
          draft: true
          files: ${{ matrix.job.name }}/rustdesk-server-${{ matrix.job.os }}-${{ matrix.job.name }}${{ matrix.job.suffix }}.zip
            
  # docker build and push of single-arch images
  docker:

    name: Docker push - ${{ matrix.job.name }}
    needs: build
    runs-on: ubuntu-22.04
    strategy:
      fail-fast: false
      matrix:
        job:
          - { name: "amd64",   docker_platform: "linux/amd64",  s6_platform: "x86_64" }
          - { name: "arm64v8", docker_platform: "linux/arm64",  s6_platform: "aarch64" }
          - { name: "armv7",   docker_platform: "linux/arm/v7", s6_platform: "armhf" }
          - { name: "i386",    docker_platform: "linux/386",    s6_platform: "i686" }

    steps:

      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive
        
      - name: Download binaries
        uses: actions/download-artifact@v4
        with:
          name: binaries-linux-${{ matrix.job.name }}
          path: docker/rootfs/usr/bin

      - name: Make binaries executable
        run: chmod -v a+x docker/rootfs/usr/bin/*

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2
      
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Log in to Docker Hub
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}

      - name: Log in to GHCR
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: rustdesk
          password: ${{ secrets.GITHUB_TOKEN }}
        
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: registry.hub.docker.com/${{ secrets.DOCKER_IMAGE }}

      - name: Get git tag
        id: vars
        run: |
          T=${GITHUB_REF#refs/*/}
          M=${T%%.*}
          echo "GIT_TAG=$T" >> $GITHUB_ENV
          echo "MAJOR_TAG=$M" >> $GITHUB_ENV

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: "./docker"
          platforms: ${{ matrix.job.docker_platform }}
          push: true
          provenance: false
          build-args: |
            S6_ARCH=${{ matrix.job.s6_platform }}
          tags: |
            ${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}-${{ matrix.job.name }}
            ${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}-${{ matrix.job.name }}
            ${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}-${{ matrix.job.name }}
          labels: ${{ steps.meta.outputs.labels }}

  # docker build and push of multiarch images
  docker-manifest:

    name: Docker manifest
    needs: docker
    runs-on: ubuntu-22.04

    steps:

      - name: Log in to Docker Hub
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}

      - name: Get git tag
        id: vars
        run: |
          T=${GITHUB_REF#refs/*/}
          M=${T%%.*}
          echo "GIT_TAG=$T" >> $GITHUB_ENV
          echo "MAJOR_TAG=$M" >> $GITHUB_ENV

      - name: Log in to GHCR
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: rustdesk
          password: ${{ secrets.GITHUB_TOKEN }}

      # manifest for :1.2.3 tag
      #  this has to run only if invoked by a new tag
      - name: Create and push manifest (:ve.rs.ion)
        uses: Noelware/docker-manifest-action@0.4.3
        if: github.event_name != 'workflow_dispatch'
        with:
          base-image: ${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}-amd64,${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}-armv7,${{ secrets.DOCKER_IMAGE }}:${{ env.GIT_TAG }}-i386
          push: true

      # manifest for :1 tag (major release)
      - name: Create and push manifest (:major)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}-amd64,${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}-armv7,${{ secrets.DOCKER_IMAGE }}:${{ env.MAJOR_TAG }}-i386
          push: true

      # manifest for :latest tag
      - name: Create and push manifest (:latest)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}-amd64,${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}-armv7,${{ secrets.DOCKER_IMAGE }}:${{ env.LATEST_TAG }}-i386
          push: true

      # GHCR manifests
      # manifest for :1.2.3 tag
      - name: Create and push GHCR manifest (:ve.rs.ion)
        uses: Noelware/docker-manifest-action@0.4.3
        if: github.event_name != 'workflow_dispatch'
        with:
          base-image: ${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}
          extra-images: ${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}-amd64,${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}-arm64v8,${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}-armv7,${{ env.GHCR_IMAGE }}:${{ env.GIT_TAG }}-i386
          push: true

      # manifest for :1 tag (major release)
      - name: Create and push GHCR manifest (:major)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}
          extra-images: ${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}-amd64,${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}-arm64v8,${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}-armv7,${{ env.GHCR_IMAGE }}:${{ env.MAJOR_TAG }}-i386
          push: true

      # manifest for :latest tag
      - name: Create and push GHCR manifest (:latest)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}
          extra-images: ${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}-amd64,${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}-arm64v8,${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}-armv7,${{ env.GHCR_IMAGE }}:${{ env.LATEST_TAG }}-i386
          push: true

            
  # docker build and push of single-arch images
  docker-classic:

    name: Docker push - ${{ matrix.job.name }}
    needs: build
    runs-on: ubuntu-22.04
    strategy:
      fail-fast: false
      matrix:
        job:
          - { name: "amd64",   docker_platform: "linux/amd64" }
          - { name: "arm64v8", docker_platform: "linux/arm64" }
          - { name: "armv7",   docker_platform: "linux/arm/v7" }

    steps:

      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive
        
      - name: Download binaries
        uses: actions/download-artifact@v4
        with:
          name: binaries-linux-${{ matrix.job.name }}
          path: docker-classic/

      - name: Make binaries executable
        run: chmod -v a+x docker-classic/*

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2
      
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Log in to Docker Hub
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}

      - name: Log in to GHCR
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: rustdesk
          password: ${{ secrets.GITHUB_TOKEN }}
        
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: registry.hub.docker.com/${{ secrets.DOCKER_IMAGE_CLASSIC }}

      - name: Get git tag
        id: vars
        run: |
          T=${GITHUB_REF#refs/*/}
          M=${T%%.*}
          echo "GIT_TAG=$T" >> $GITHUB_ENV
          echo "MAJOR_TAG=$M" >> $GITHUB_ENV

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: "./docker-classic"
          platforms: ${{ matrix.job.docker_platform }}
          push: true
          provenance: false
          tags: |
            ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-${{ matrix.job.name }}
            ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-${{ matrix.job.name }}
            ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-${{ matrix.job.name }}
            ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-${{ matrix.job.name }}
          labels: ${{ steps.meta.outputs.labels }}

  # docker build and push of multiarch images
  docker-manifest-classic:

    name: Docker manifest
    needs: docker
    runs-on: ubuntu-22.04

    steps:

      - name: Log in to Docker Hub
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}

      - name: Get git tag
        id: vars
        run: |
          T=${GITHUB_REF#refs/*/}
          M=${T%%.*}
          echo "GIT_TAG=$T" >> $GITHUB_ENV
          echo "MAJOR_TAG=$M" >> $GITHUB_ENV

      - name: Log in to GHCR
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: rustdesk
          password: ${{ secrets.GITHUB_TOKEN }}

      # manifest for :1.2.3 tag
      #  this has to run only if invoked by a new tag
      - name: Create and push manifest (:ve.rs.ion)
        uses: Noelware/docker-manifest-action@0.4.3
        if: github.event_name != 'workflow_dispatch'
        with:
          base-image: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-amd64,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-armv7
          push: true

      # manifest for :1 tag (major release)
      - name: Create and push manifest (:major)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-amd64,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-armv7
          push: true

      # manifest for :latest tag
      - name: Create and push manifest (:latest)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}
          extra-images: ${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-amd64,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-arm64v8,${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-armv7
          push: true

      # GHCR manifests
      # manifest for :1.2.3 tag
      - name: Create and push GHCR manifest (:ve.rs.ion)
        uses: Noelware/docker-manifest-action@0.4.3
        if: github.event_name != 'workflow_dispatch'
        with:
          base-image: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}
          extra-images: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-amd64,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-arm64v8,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.GIT_TAG }}-armv7
          push: true

      # manifest for :1 tag (major release)
      - name: Create and push GHCR manifest (:major)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}
          extra-images: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-amd64,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-arm64v8,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.MAJOR_TAG }}-armv7
          push: true

      # manifest for :latest tag
      - name: Create and push GHCR manifest (:latest)
        uses: Noelware/docker-manifest-action@0.4.3
        with:
          base-image: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}
          extra-images: ${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-amd64,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-arm64v8,${{ env.GHCR_IMAGE_CLASSIC }}:${{ env.LATEST_TAG }}-armv7
          push: true


  deb-package:

    name: debian package - ${{ matrix.job.name }}
    needs: build
    runs-on: ubuntu-22.04
    strategy:
      fail-fast: false
      matrix:
        job:
          - { name: "amd64",   debian_platform: "amd64",   crossbuild_package: "" }
          - { name: "arm64v8", debian_platform: "arm64",   crossbuild_package: "crossbuild-essential-arm64" }
          - { name: "armv7",   debian_platform: "armhf",   crossbuild_package: "crossbuild-essential-armhf" }
          - { name: "i386",    debian_platform: "i386",    crossbuild_package: "crossbuild-essential-i386" }

    steps:

      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2

      - name: Create packaging env
        run: |
          sudo apt update
          DEBIAN_FRONTEND=noninteractive sudo apt install -y devscripts build-essential debhelper pkg-config ${{ matrix.job.crossbuild_package }}
          mkdir -p debian-build/${{ matrix.job.name }}/bin

      - name: Download binaries
        uses: actions/download-artifact@v4
        with:
          name: binaries-linux-${{ matrix.job.name }}
          path: debian-build/${{ matrix.job.name }}/bin

      - name: Build package for ${{ matrix.job.name }} arch
        run: |
          chmod -v a+x debian-build/${{ matrix.job.name }}/bin/*
          cp -vr debian systemd debian-build/${{ matrix.job.name }}/
          cat debian/control.tpl | sed 's/{{ ARCH }}/${{ matrix.job.debian_platform }}/' > debian-build/${{ matrix.job.name }}/debian/control
          cd debian-build/${{ matrix.job.name }}/
          debuild -i -us -uc -b -a${{ matrix.job.debian_platform }}

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          draft: true
          files: |
            debian-build/rustdesk-server-hbbr_*_${{ matrix.job.debian_platform }}.deb
            debian-build/rustdesk-server-hbbs_*_${{ matrix.job.debian_platform }}.deb
            debian-build/rustdesk-server-utils_*_${{ matrix.job.debian_platform }}.deb


================================================
FILE: .gitignore
================================================
target
id*
db*
debian-build
debian/.debhelper
debian/debhelper-build-stamp
.DS_Store
.vscode
src/version.rs
db_v2.sqlite3
test.*
.idea


================================================
FILE: .gitmodules
================================================
[submodule "libs/hbb_common"]
	path = libs/hbb_common
	url = https://github.com/rustdesk/hbb_common


================================================
FILE: Cargo.toml
================================================
[package]
name = "hbbs"
version = "1.1.15"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2021"
build = "build.rs"
default-run = "hbbs"

[[bin]]
name = "hbbr"
path = "src/hbbr.rs"

[[bin]]
name = "rustdesk-utils"
path = "src/utils.rs"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
hbb_common = { path = "libs/hbb_common" }
serde_derive = "1.0"
serde = "1.0"
serde_json = "1.0"
lazy_static = "1.4"
clap = "2"
rust-ini = "0.18"
minreq = { version = "2.4", features = ["punycode"] }
machine-uid = "0.2"
mac_address = "1.1.5"
whoami = "1.2"
base64 = "0.13"
axum = { version = "0.5", features = ["headers"] }
sqlx = { version = "0.6", features = [ "runtime-tokio-rustls", "sqlite", "macros", "chrono", "json" ] }
deadpool = "0.8"
async-trait = "0.1"
async-speed-limit = { git = "https://github.com/open-trade/async-speed-limit" }
uuid = { version = "1.0", features = ["v4"] }
bcrypt = "0.13"
chrono = "0.4"
jsonwebtoken = "8"
headers = "0.3"
once_cell = "1.8"
sodiumoxide = "0.2"
tokio-tungstenite = "0.17"
tungstenite = "0.17"
regex = "1.4"
tower-http = { version = "0.3", features = ["fs", "trace", "cors"] }
http = "0.2"
flexi_logger = { version = "0.22", features = ["async", "use_chrono_for_offset", "dont_minimize_extra_stacks"] }
ipnetwork = "0.20"
local-ip-address = "0.5.1"
dns-lookup = "1.0.8"
ping = "0.4.0"
flate2 = "1.0"

[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]
# https://github.com/rustdesk/rustdesk-server-pro/issues/189, using native-tls for better tls support
reqwest = { git = "https://github.com/rustdesk-org/reqwest", features = ["blocking", "socks", "json", "native-tls", "gzip"], default-features=false }

[target.'cfg(not(any(target_os = "macos", target_os = "windows")))'.dependencies]
reqwest = { git = "https://github.com/rustdesk-org/reqwest", features = ["blocking", "socks", "json", "rustls-tls", "rustls-tls-native-roots", "gzip"], default-features=false }

[build-dependencies]
hbb_common = { path = "libs/hbb_common" }

[workspace]
members = ["libs/hbb_common"]
exclude = ["ui"]

#https://github.com/johnthagen/min-sized-rust
#https://doc.rust-lang.org/cargo/reference/profiles.html#default-profiles
[profile.release]
lto = true
codegen-units = 1
panic = 'abort'
strip = true
#opt-level = 'z' # only have smaller size after strip # Default is 3, better performance
#rpath = true # Not needed


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# RustDesk Server Program

[![build](https://github.com/rustdesk/rustdesk-server/actions/workflows/build.yaml/badge.svg)](https://github.com/rustdesk/rustdesk-server/actions/workflows/build.yaml)

[**Download**](https://github.com/rustdesk/rustdesk-server/releases)

[**Manual**](https://rustdesk.com/docs/en/self-host/)

[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/FAQ)

[**How to migrate OSS to Pro**](https://rustdesk.com/docs/en/self-host/rustdesk-server-pro/installscript/#convert-from-open-source)

Self-host your own RustDesk server, it is free and open source.

## How to build manually

```bash
cargo build --release
```

Three executables will be generated in target/release.

- hbbs - RustDesk ID/Rendezvous server
- hbbr - RustDesk relay server
- rustdesk-utils - RustDesk CLI utilities

You can find updated binaries on the [Releases](https://github.com/rustdesk/rustdesk-server/releases) page.

If you want extra features, [RustDesk Server Pro](https://rustdesk.com/pricing.html) might suit you better.

If you want to develop your own server, [rustdesk-server-demo](https://github.com/rustdesk/rustdesk-server-demo) might be a better and simpler start for you than this repo.

## Installation

Please follow this [doc](https://rustdesk.com/docs/en/self-host/rustdesk-server-oss/)


================================================
FILE: build.rs
================================================
fn main() {
    hbb_common::gen_version();
}


================================================
FILE: debian/README.source
================================================
#
# Juli Augustus 2025 was building the downloadable Debian packages done
# by github.com CI, meaning you being depended on github.com
# for getting a .deb of the libre source code (four GNU freedoms) you have.
#
# And in those days there was no official Debian package.
#
# What follows are instructions that make it possible to do
# a succesfull
#
#   debuild -uc -us
#
# in the directory  target/rustdesk-server
#
# The instructions are written in bash syntax,
#
#   bash debian/README.source
#
# should help you immens
#

# Make sure the submodules are present
git submodule update --init --recursive

rm -rf target/rustdesk-server  # avoid clutter from previous iteration
mkdir -p target/rustdesk-server #  FYI: target/ is ignored by git

tar cf - \
    --exclude .git \
    Cargo.toml Cargo.lock \
	LICENSE README.md \
    db_v2.sqlite3 \
	build.rs \
	debian \
	libs rcd src \
    systemd ui \
| ( cd target/rustdesk-server && tar x )

mv target/rustdesk-server/debian/Makefile target/rustdesk-server/

tar cjf target/rustdesk-server-orig.tar.xz \
    --strip-components=1 \
    target/rustdesk-server

# an .orig.tar.xz tarball exists, 
# work on the debian directory 

eval $( dpkg-architecture )
sed -e "s/{{ ARCH }}/${DEB_TARGET_ARCH}/" \
    debian/control.tpl > target/rustdesk-server/debian/control
    

cd target/rustdesk-server
dpkg-checkbuilddeps || echo sudo apt install dpkg-dev
debuild -uc -us

#
# For what it is worth:
# Early September 2025 there were
# several WARNINGS and ERRORS from Lintian
#
# l l


================================================
FILE: debian/changelog
================================================
rustdesk-server (1.1.15) UNRELEASED; urgency=medium

  * Fix: 127.0.0.1 is not loopback (#515)
  * Higher default bandwidth
  * Define the HOME env to allow running rootless (#612)
  * Add option to log (failed) authentication attempts to enable the usage of tools like fail2ban and crowdsec (#435)
  * Connection log query
 
 -- rustdesk <info@rustdesk.com>  Sat, 10 Jan 2026 16:04:19 +0800

rustdesk-server (1.1.14) UNRELEASED; urgency=medium

  * Fix windows crash

 -- rustdesk <info@rustdesk.com>  Sat, 25 Jan 2025 20:47:19 +0800

rustdesk-server (1.1.13) UNRELEASED; urgency=medium

  * Version check and refactor hbb_common to share with rustdesk client

 -- rustdesk <info@rustdesk.com>  Tue, 21 Jan 2025 01:33:42 +0800

rustdesk-server (1.1.12) UNRELEASED; urgency=medium

  * WS real ip
  * Bump s6-overlay to v3.2.0.0 and fix env warnings

 -- rustdesk <info@rustdesk.com>  Mon, 7 Oct 2024 16:21:36 +0800

rustdesk-server (1.1.11-1) UNRELEASED; urgency=medium

  * set reuse port to make restart friendly
  * revert hbbr `-k` to not ruin back-compatibility

 -- rustdesk <info@rustdesk.com>  Fri, 24 May 2024 18:37:11 +0800

rustdesk-server (1.1.11) UNRELEASED; urgency=medium

  * change -k to default '-', so you need not to set -k any more

 -- rustdesk <info@rustdesk.com>  Fri, 24 May 2024 18:09:12 +0800

rustdesk-server (1.1.10-3) UNRELEASED; urgency=medium

  * fix on -2

 -- rustdesk <info@rustdesk.com>  Wed, 31 Jan 2024 11:30:42 +0800

rustdesk-server (1.1.10-2) UNRELEASED; urgency=medium

  * fix hangup signal exit when run with nohup
  * some minors

 -- rustdesk <info@rustdesk.com>  Tue, 30 Jan 2024 19:23:36 +0800

rustdesk-server (1.1.9) UNRELEASED; urgency=medium

  * remove unsafe

 -- rustdesk <info@rustdesk.com>  Tue, 5 Dec 2023 17:22:40 +0800

rustdesk-server (1.1.8) UNRELEASED; urgency=medium

  * fix test_hbbs and mask in lan

 -- rustdesk <info@rustdesk.com>  Thu, 6 Jul 2023 00:50:11 +0800

rustdesk-server (1.1.7) UNRELEASED; urgency=medium

  * ipv6 support

 -- rustdesk <info@rustdesk.com>  Wed, 11 Jan 2023 11:27:00 +0800

rustdesk-server (1.1.6) UNRELEASED; urgency=medium

  * Initial release

 -- open-trade <info@rustdesk.com>  Fri, 15 Jul 2022 12:27:27 +0200


================================================
FILE: debian/compat
================================================
10


================================================
FILE: debian/control.tpl
================================================
Source: rustdesk-server
Section: net
Priority: optional
Maintainer: open-trade <info@rustdesk.com>
Build-Depends: debhelper (>= 10), pkg-config
Standards-Version: 4.5.0
Homepage: https://rustdesk.com/

Package: rustdesk-server-hbbs
Architecture: {{ ARCH }}
Depends: systemd ${misc:Depends}
Description: RustDesk server
 Self-host your own RustDesk server, it is free and open source.

Package: rustdesk-server-hbbr
Architecture: {{ ARCH }}
Depends: systemd ${misc:Depends}
Description: RustDesk server
 Self-host your own RustDesk server, it is free and open source.
 This package contains the RustDesk relay server.

Package: rustdesk-server-utils
Architecture: {{ ARCH }}
Depends: ${misc:Depends}
Description: RustDesk server
 Self-host your own RustDesk server, it is free and open source.
 This package contains the rustdesk-utils binary.


================================================
FILE: debian/copyright
================================================
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: rustdesk-server
Files: *
Copyright: Copyright 2022 open-trade <info@rustdesk.com>
License: AGPL-3.0
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 .
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.
 .
 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 .
                     GNU AFFERO GENERAL PUBLIC LICENSE
                        Version 3, 19 November 2007
 .
  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 .
                             Preamble
 .
   The GNU Affero General Public License is a free, copyleft license for
 software and other kinds of works, specifically designed to ensure
 cooperation with the community in the case of network server software.
 .
   The licenses for most software and other practical works are designed
 to take away your freedom to share and change the works.  By contrast,
 our General Public Licenses are intended to guarantee your freedom to
 share and change all versions of a program--to make sure it remains free
 software for all its users.
 .
   When we speak of free software, we are referring to freedom, not
 price.  Our General Public Licenses are designed to make sure that you
 have the freedom to distribute copies of free software (and charge for
 them if you wish), that you receive source code or can get it if you
 want it, that you can change the software or use pieces of it in new
 free programs, and that you know you can do these things.
 .
   Developers that use our General Public Licenses protect your rights
 with two steps: (1) assert copyright on the software, and (2) offer
 you this License which gives you legal permission to copy, distribute
 and/or modify the software.
 .
   A secondary benefit of defending all users' freedom is that
 improvements made in alternate versions of the program, if they
 receive widespread use, become available for other developers to
 incorporate.  Many developers of free software are heartened and
 encouraged by the resulting cooperation.  However, in the case of
 software used on network servers, this result may fail to come about.
 The GNU General Public License permits making a modified version and
 letting the public access it on a server without ever releasing its
 source code to the public.
 .
   The GNU Affero General Public License is designed specifically to
 ensure that, in such cases, the modified source code becomes available
 to the community.  It requires the operator of a network server to
 provide the source code of the modified version running there to the
 users of that server.  Therefore, public use of a modified version, on
 a publicly accessible server, gives the public access to the source
 code of the modified version.
 .
   An older license, called the Affero General Public License and
 published by Affero, was designed to accomplish similar goals.  This is
 a different license, not a version of the Affero GPL, but Affero has
 released a new version of the Affero GPL which permits relicensing under
 this license.
 .
   The precise terms and conditions for copying, distribution and
 modification follow.
 .
                        TERMS AND CONDITIONS
 .
   0. Definitions.
 .
   "This License" refers to version 3 of the GNU Affero General Public License.
 .
   "Copyright" also means copyright-like laws that apply to other kinds of
 works, such as semiconductor masks.
 .
   "The Program" refers to any copyrightable work licensed under this
 License.  Each licensee is addressed as "you".  "Licensees" and
 "recipients" may be individuals or organizations.
 .
   To "modify" a work means to copy from or adapt all or part of the work
 in a fashion requiring copyright permission, other than the making of an
 exact copy.  The resulting work is called a "modified version" of the
 earlier work or a work "based on" the earlier work.
 .
   A "covered work" means either the unmodified Program or a work based
 on the Program.
 .
   To "propagate" a work means to do anything with it that, without
 permission, would make you directly or secondarily liable for
 infringement under applicable copyright law, except executing it on a
 computer or modifying a private copy.  Propagation includes copying,
 distribution (with or without modification), making available to the
 public, and in some countries other activities as well.
 .
   To "convey" a work means any kind of propagation that enables other
 parties to make or receive copies.  Mere interaction with a user through
 a computer network, with no transfer of a copy, is not conveying.
 .
   An interactive user interface displays "Appropriate Legal Notices"
 to the extent that it includes a convenient and prominently visible
 feature that (1) displays an appropriate copyright notice, and (2)
 tells the user that there is no warranty for the work (except to the
 extent that warranties are provided), that licensees may convey the
 work under this License, and how to view a copy of this License.  If
 the interface presents a list of user commands or options, such as a
 menu, a prominent item in the list meets this criterion.
 .
   1. Source Code.
 .
   The "source code" for a work means the preferred form of the work
 for making modifications to it.  "Object code" means any non-source
 form of a work.
 .
   A "Standard Interface" means an interface that either is an official
 standard defined by a recognized standards body, or, in the case of
 interfaces specified for a particular programming language, one that
 is widely used among developers working in that language.
 .
   The "System Libraries" of an executable work include anything, other
 than the work as a whole, that (a) is included in the normal form of
 packaging a Major Component, but which is not part of that Major
 Component, and (b) serves only to enable use of the work with that
 Major Component, or to implement a Standard Interface for which an
 implementation is available to the public in source code form.  A
 "Major Component", in this context, means a major essential component
 (kernel, window system, and so on) of the specific operating system
 (if any) on which the executable work runs, or a compiler used to
 produce the work, or an object code interpreter used to run it.
 .
   The "Corresponding Source" for a work in object code form means all
 the source code needed to generate, install, and (for an executable
 work) run the object code and to modify the work, including scripts to
 control those activities.  However, it does not include the work's
 System Libraries, or general-purpose tools or generally available free
 programs which are used unmodified in performing those activities but
 which are not part of the work.  For example, Corresponding Source
 includes interface definition files associated with source files for
 the work, and the source code for shared libraries and dynamically
 linked subprograms that the work is specifically designed to require,
 such as by intimate data communication or control flow between those
 subprograms and other parts of the work.
 .
   The Corresponding Source need not include anything that users
 can regenerate automatically from other parts of the Corresponding
 Source.
 .
   The Corresponding Source for a work in source code form is that
 same work.
 .
   2. Basic Permissions.
 .
   All rights granted under this License are granted for the term of
 copyright on the Program, and are irrevocable provided the stated
 conditions are met.  This License explicitly affirms your unlimited
 permission to run the unmodified Program.  The output from running a
 covered work is covered by this License only if the output, given its
 content, constitutes a covered work.  This License acknowledges your
 rights of fair use or other equivalent, as provided by copyright law.
 .
   You may make, run and propagate covered works that you do not
 convey, without conditions so long as your license otherwise remains
 in force.  You may convey covered works to others for the sole purpose
 of having them make modifications exclusively for you, or provide you
 with facilities for running those works, provided that you comply with
 the terms of this License in conveying all material for which you do
 not control copyright.  Those thus making or running the covered works
 for you must do so exclusively on your behalf, under your direction
 and control, on terms that prohibit them from making any copies of
 your copyrighted material outside their relationship with you.
 .
   Conveying under any other circumstances is permitted solely under
 the conditions stated below.  Sublicensing is not allowed; section 10
 makes it unnecessary.
 .
   3. Protecting Users' Legal Rights From Anti-Circumvention Law.
 .
   No covered work shall be deemed part of an effective technological
 measure under any applicable law fulfilling obligations under article
 11 of the WIPO copyright treaty adopted on 20 December 1996, or
 similar laws prohibiting or restricting circumvention of such
 measures.
 .
   When you convey a covered work, you waive any legal power to forbid
 circumvention of technological measures to the extent such circumvention
 is effected by exercising rights under this License with respect to
 the covered work, and you disclaim any intention to limit operation or
 modification of the work as a means of enforcing, against the work's
 users, your or third parties' legal rights to forbid circumvention of
 technological measures.
 .
   4. Conveying Verbatim Copies.
 .
   You may convey verbatim copies of the Program's source code as you
 receive it, in any medium, provided that you conspicuously and
 appropriately publish on each copy an appropriate copyright notice;
 keep intact all notices stating that this License and any
 non-permissive terms added in accord with section 7 apply to the code;
 keep intact all notices of the absence of any warranty; and give all
 recipients a copy of this License along with the Program.
 .
   You may charge any price or no price for each copy that you convey,
 and you may offer support or warranty protection for a fee.
 .
   5. Conveying Modified Source Versions.
 .
   You may convey a work based on the Program, or the modifications to
 produce it from the Program, in the form of source code under the
 terms of section 4, provided that you also meet all of these conditions:
 .
     a) The work must carry prominent notices stating that you modified
     it, and giving a relevant date.
 .
     b) The work must carry prominent notices stating that it is
     released under this License and any conditions added under section
     7.  This requirement modifies the requirement in section 4 to
     "keep intact all notices".
 .
     c) You must license the entire work, as a whole, under this
     License to anyone who comes into possession of a copy.  This
     License will therefore apply, along with any applicable section 7
     additional terms, to the whole of the work, and all its parts,
     regardless of how they are packaged.  This License gives no
     permission to license the work in any other way, but it does not
     invalidate such permission if you have separately received it.
 .
     d) If the work has interactive user interfaces, each must display
     Appropriate Legal Notices; however, if the Program has interactive
     interfaces that do not display Appropriate Legal Notices, your
     work need not make them do so.
 .
   A compilation of a covered work with other separate and independent
 works, which are not by their nature extensions of the covered work,
 and which are not combined with it such as to form a larger program,
 in or on a volume of a storage or distribution medium, is called an
 "aggregate" if the compilation and its resulting copyright are not
 used to limit the access or legal rights of the compilation's users
 beyond what the individual works permit.  Inclusion of a covered work
 in an aggregate does not cause this License to apply to the other
 parts of the aggregate.
 .
   6. Conveying Non-Source Forms.
 .
   You may convey a covered work in object code form under the terms
 of sections 4 and 5, provided that you also convey the
 machine-readable Corresponding Source under the terms of this License,
 in one of these ways:
 .
     a) Convey the object code in, or embodied in, a physical product
     (including a physical distribution medium), accompanied by the
     Corresponding Source fixed on a durable physical medium
     customarily used for software interchange.
 .
     b) Convey the object code in, or embodied in, a physical product
     (including a physical distribution medium), accompanied by a
     written offer, valid for at least three years and valid for as
     long as you offer spare parts or customer support for that product
     model, to give anyone who possesses the object code either (1) a
     copy of the Corresponding Source for all the software in the
     product that is covered by this License, on a durable physical
     medium customarily used for software interchange, for a price no
     more than your reasonable cost of physically performing this
     conveying of source, or (2) access to copy the
     Corresponding Source from a network server at no charge.
 .
     c) Convey individual copies of the object code with a copy of the
     written offer to provide the Corresponding Source.  This
     alternative is allowed only occasionally and noncommercially, and
     only if you received the object code with such an offer, in accord
     with subsection 6b.
 .
     d) Convey the object code by offering access from a designated
     place (gratis or for a charge), and offer equivalent access to the
     Corresponding Source in the same way through the same place at no
     further charge.  You need not require recipients to copy the
     Corresponding Source along with the object code.  If the place to
     copy the object code is a network server, the Corresponding Source
     may be on a different server (operated by you or a third party)
     that supports equivalent copying facilities, provided you maintain
     clear directions next to the object code saying where to find the
     Corresponding Source.  Regardless of what server hosts the
     Corresponding Source, you remain obligated to ensure that it is
     available for as long as needed to satisfy these requirements.
 .
     e) Convey the object code using peer-to-peer transmission, provided
     you inform other peers where the object code and Corresponding
     Source of the work are being offered to the general public at no
     charge under subsection 6d.
 .
   A separable portion of the object code, whose source code is excluded
 from the Corresponding Source as a System Library, need not be
 included in conveying the object code work.
 .
   A "User Product" is either (1) a "consumer product", which means any
 tangible personal property which is normally used for personal, family,
 or household purposes, or (2) anything designed or sold for incorporation
 into a dwelling.  In determining whether a product is a consumer product,
 doubtful cases shall be resolved in favor of coverage.  For a particular
 product received by a particular user, "normally used" refers to a
 typical or common use of that class of product, regardless of the status
 of the particular user or of the way in which the particular user
 actually uses, or expects or is expected to use, the product.  A product
 is a consumer product regardless of whether the product has substantial
 commercial, industrial or non-consumer uses, unless such uses represent
 the only significant mode of use of the product.
 .
   "Installation Information" for a User Product means any methods,
 procedures, authorization keys, or other information required to install
 and execute modified versions of a covered work in that User Product from
 a modified version of its Corresponding Source.  The information must
 suffice to ensure that the continued functioning of the modified object
 code is in no case prevented or interfered with solely because
 modification has been made.
 .
   If you convey an object code work under this section in, or with, or
 specifically for use in, a User Product, and the conveying occurs as
 part of a transaction in which the right of possession and use of the
 User Product is transferred to the recipient in perpetuity or for a
 fixed term (regardless of how the transaction is characterized), the
 Corresponding Source conveyed under this section must be accompanied
 by the Installation Information.  But this requirement does not apply
 if neither you nor any third party retains the ability to install
 modified object code on the User Product (for example, the work has
 been installed in ROM).
 .
   The requirement to provide Installation Information does not include a
 requirement to continue to provide support service, warranty, or updates
 for a work that has been modified or installed by the recipient, or for
 the User Product in which it has been modified or installed.  Access to a
 network may be denied when the modification itself materially and
 adversely affects the operation of the network or violates the rules and
 protocols for communication across the network.
 .
   Corresponding Source conveyed, and Installation Information provided,
 in accord with this section must be in a format that is publicly
 documented (and with an implementation available to the public in
 source code form), and must require no special password or key for
 unpacking, reading or copying.
 .
   7. Additional Terms.
 .
   "Additional permissions" are terms that supplement the terms of this
 License by making exceptions from one or more of its conditions.
 Additional permissions that are applicable to the entire Program shall
 be treated as though they were included in this License, to the extent
 that they are valid under applicable law.  If additional permissions
 apply only to part of the Program, that part may be used separately
 under those permissions, but the entire Program remains governed by
 this License without regard to the additional permissions.
 .
   When you convey a copy of a covered work, you may at your option
 remove any additional permissions from that copy, or from any part of
 it.  (Additional permissions may be written to require their own
 removal in certain cases when you modify the work.)  You may place
 additional permissions on material, added by you to a covered work,
 for which you have or can give appropriate copyright permission.
 .
   Notwithstanding any other provision of this License, for material you
 add to a covered work, you may (if authorized by the copyright holders of
 that material) supplement the terms of this License with terms:
 .
     a) Disclaiming warranty or limiting liability differently from the
     terms of sections 15 and 16 of this License; or
 .
     b) Requiring preservation of specified reasonable legal notices or
     author attributions in that material or in the Appropriate Legal
     Notices displayed by works containing it; or
 .
     c) Prohibiting misrepresentation of the origin of that material, or
     requiring that modified versions of such material be marked in
     reasonable ways as different from the original version; or
 .
     d) Limiting the use for publicity purposes of names of licensors or
     authors of the material; or
 .
     e) Declining to grant rights under trademark law for use of some
     trade names, trademarks, or service marks; or
 .
     f) Requiring indemnification of licensors and authors of that
     material by anyone who conveys the material (or modified versions of
     it) with contractual assumptions of liability to the recipient, for
     any liability that these contractual assumptions directly impose on
     those licensors and authors.
 .
   All other non-permissive additional terms are considered "further
 restrictions" within the meaning of section 10.  If the Program as you
 received it, or any part of it, contains a notice stating that it is
 governed by this License along with a term that is a further
 restriction, you may remove that term.  If a license document contains
 a further restriction but permits relicensing or conveying under this
 License, you may add to a covered work material governed by the terms
 of that license document, provided that the further restriction does
 not survive such relicensing or conveying.
 .
   If you add terms to a covered work in accord with this section, you
 must place, in the relevant source files, a statement of the
 additional terms that apply to those files, or a notice indicating
 where to find the applicable terms.
 .
   Additional terms, permissive or non-permissive, may be stated in the
 form of a separately written license, or stated as exceptions;
 the above requirements apply either way.
 .
   8. Termination.
 .
   You may not propagate or modify a covered work except as expressly
 provided under this License.  Any attempt otherwise to propagate or
 modify it is void, and will automatically terminate your rights under
 this License (including any patent licenses granted under the third
 paragraph of section 11).
 .
   However, if you cease all violation of this License, then your
 license from a particular copyright holder is reinstated (a)
 provisionally, unless and until the copyright holder explicitly and
 finally terminates your license, and (b) permanently, if the copyright
 holder fails to notify you of the violation by some reasonable means
 prior to 60 days after the cessation.
 .
   Moreover, your license from a particular copyright holder is
 reinstated permanently if the copyright holder notifies you of the
 violation by some reasonable means, this is the first time you have
 received notice of violation of this License (for any work) from that
 copyright holder, and you cure the violation prior to 30 days after
 your receipt of the notice.
 .
   Termination of your rights under this section does not terminate the
 licenses of parties who have received copies or rights from you under
 this License.  If your rights have been terminated and not permanently
 reinstated, you do not qualify to receive new licenses for the same
 material under section 10.
 .
   9. Acceptance Not Required for Having Copies.
 .
   You are not required to accept this License in order to receive or
 run a copy of the Program.  Ancillary propagation of a covered work
 occurring solely as a consequence of using peer-to-peer transmission
 to receive a copy likewise does not require acceptance.  However,
 nothing other than this License grants you permission to propagate or
 modify any covered work.  These actions infringe copyright if you do
 not accept this License.  Therefore, by modifying or propagating a
 covered work, you indicate your acceptance of this License to do so.
 .
   10. Automatic Licensing of Downstream Recipients.
 .
   Each time you convey a covered work, the recipient automatically
 receives a license from the original licensors, to run, modify and
 propagate that work, subject to this License.  You are not responsible
 for enforcing compliance by third parties with this License.
 .
   An "entity transaction" is a transaction transferring control of an
 organization, or substantially all assets of one, or subdividing an
 organization, or merging organizations.  If propagation of a covered
 work results from an entity transaction, each party to that
 transaction who receives a copy of the work also receives whatever
 licenses to the work the party's predecessor in interest had or could
 give under the previous paragraph, plus a right to possession of the
 Corresponding Source of the work from the predecessor in interest, if
 the predecessor has it or can get it with reasonable efforts.
 .
   You may not impose any further restrictions on the exercise of the
 rights granted or affirmed under this License.  For example, you may
 not impose a license fee, royalty, or other charge for exercise of
 rights granted under this License, and you may not initiate litigation
 (including a cross-claim or counterclaim in a lawsuit) alleging that
 any patent claim is infringed by making, using, selling, offering for
 sale, or importing the Program or any portion of it.
 .
   11. Patents.
 .
   A "contributor" is a copyright holder who authorizes use under this
 License of the Program or a work on which the Program is based.  The
 work thus licensed is called the contributor's "contributor version".
 .
   A contributor's "essential patent claims" are all patent claims
 owned or controlled by the contributor, whether already acquired or
 hereafter acquired, that would be infringed by some manner, permitted
 by this License, of making, using, or selling its contributor version,
 but do not include claims that would be infringed only as a
 consequence of further modification of the contributor version.  For
 purposes of this definition, "control" includes the right to grant
 patent sublicenses in a manner consistent with the requirements of
 this License.
 .
   Each contributor grants you a non-exclusive, worldwide, royalty-free
 patent license under the contributor's essential patent claims, to
 make, use, sell, offer for sale, import and otherwise run, modify and
 propagate the contents of its contributor version.
 .
   In the following three paragraphs, a "patent license" is any express
 agreement or commitment, however denominated, not to enforce a patent
 (such as an express permission to practice a patent or covenant not to
 sue for patent infringement).  To "grant" such a patent license to a
 party means to make such an agreement or commitment not to enforce a
 patent against the party.
 .
   If you convey a covered work, knowingly relying on a patent license,
 and the Corresponding Source of the work is not available for anyone
 to copy, free of charge and under the terms of this License, through a
 publicly available network server or other readily accessible means,
 then you must either (1) cause the Corresponding Source to be so
 available, or (2) arrange to deprive yourself of the benefit of the
 patent license for this particular work, or (3) arrange, in a manner
 consistent with the requirements of this License, to extend the patent
 license to downstream recipients.  "Knowingly relying" means you have
 actual knowledge that, but for the patent license, your conveying the
 covered work in a country, or your recipient's use of the covered work
 in a country, would infringe one or more identifiable patents in that
 country that you have reason to believe are valid.
 .
   If, pursuant to or in connection with a single transaction or
 arrangement, you convey, or propagate by procuring conveyance of, a
 covered work, and grant a patent license to some of the parties
 receiving the covered work authorizing them to use, propagate, modify
 or convey a specific copy of the covered work, then the patent license
 you grant is automatically extended to all recipients of the covered
 work and works based on it.
 .
   A patent license is "discriminatory" if it does not include within
 the scope of its coverage, prohibits the exercise of, or is
 conditioned on the non-exercise of one or more of the rights that are
 specifically granted under this License.  You may not convey a covered
 work if you are a party to an arrangement with a third party that is
 in the business of distributing software, under which you make payment
 to the third party based on the extent of your activity of conveying
 the work, and under which the third party grants, to any of the
 parties who would receive the covered work from you, a discriminatory
 patent license (a) in connection with copies of the covered work
 conveyed by you (or copies made from those copies), or (b) primarily
 for and in connection with specific products or compilations that
 contain the covered work, unless you entered into that arrangement,
 or that patent license was granted, prior to 28 March 2007.
 .
   Nothing in this License shall be construed as excluding or limiting
 any implied license or other defenses to infringement that may
 otherwise be available to you under applicable patent law.
 .
   12. No Surrender of Others' Freedom.
 .
   If conditions are imposed on you (whether by court order, agreement or
 otherwise) that contradict the conditions of this License, they do not
 excuse you from the conditions of this License.  If you cannot convey a
 covered work so as to satisfy simultaneously your obligations under this
 License and any other pertinent obligations, then as a consequence you may
 not convey it at all.  For example, if you agree to terms that obligate you
 to collect a royalty for further conveying from those to whom you convey
 the Program, the only way you could satisfy both those terms and this
 License would be to refrain entirely from conveying the Program.
 .
   13. Remote Network Interaction; Use with the GNU General Public License.
 .
   Notwithstanding any other provision of this License, if you modify the
 Program, your modified version must prominently offer all users
 interacting with it remotely through a computer network (if your version
 supports such interaction) an opportunity to receive the Corresponding
 Source of your version by providing access to the Corresponding Source
 from a network server at no charge, through some standard or customary
 means of facilitating copying of software.  This Corresponding Source
 shall include the Corresponding Source for any work covered by version 3
 of the GNU General Public License that is incorporated pursuant to the
 following paragraph.
 .
   Notwithstanding any other provision of this License, you have
 permission to link or combine any covered work with a work licensed
 under version 3 of the GNU General Public License into a single
 combined work, and to convey the resulting work.  The terms of this
 License will continue to apply to the part which is the covered work,
 but the work with which it is combined will remain governed by version
 3 of the GNU General Public License.
 .
   14. Revised Versions of this License.
 .
   The Free Software Foundation may publish revised and/or new versions of
 the GNU Affero General Public License from time to time.  Such new versions
 will be similar in spirit to the present version, but may differ in detail to
 address new problems or concerns.
 .
   Each version is given a distinguishing version number.  If the
 Program specifies that a certain numbered version of the GNU Affero General
 Public License "or any later version" applies to it, you have the
 option of following the terms and conditions either of that numbered
 version or of any later version published by the Free Software
 Foundation.  If the Program does not specify a version number of the
 GNU Affero General Public License, you may choose any version ever published
 by the Free Software Foundation.
 .
   If the Program specifies that a proxy can decide which future
 versions of the GNU Affero General Public License can be used, that proxy's
 public statement of acceptance of a version permanently authorizes you
 to choose that version for the Program.
 .
   Later license versions may give you additional or different
 permissions.  However, no additional obligations are imposed on any
 author or copyright holder as a result of your choosing to follow a
 later version.
 .
   15. Disclaimer of Warranty.
 .
   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
 APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
 HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
 OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
 IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
 ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 .
   16. Limitation of Liability.
 .
   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
 THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
 GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
 USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
 PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
 EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGES.
 .
   17. Interpretation of Sections 15 and 16.
 .
   If the disclaimer of warranty and limitation of liability provided
 above cannot be given local legal effect according to their terms,
 reviewing courts shall apply local law that most closely approximates
 an absolute waiver of all civil liability in connection with the
 Program, unless a warranty or assumption of liability accompanies a
 copy of the Program in return for a fee.
 .
                      END OF TERMS AND CONDITIONS
 .
             How to Apply These Terms to Your New Programs
 .
   If you develop a new program, and you want it to be of the greatest
 possible use to the public, the best way to achieve this is to make it
 free software which everyone can redistribute and change under these terms.
 .
   To do so, attach the following notices to the program.  It is safest
 to attach them to the start of each source file to most effectively
 state the exclusion of warranty; and each file should have at least
 the "copyright" line and a pointer to where the full notice is found.
 .
     <one line to give the program's name and a brief idea of what it does.>
     Copyright (C) <year>  <name of author>
 .
     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU Affero General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.
 .
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Affero General Public License for more details.
 .
     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 .
 Also add information on how to contact you by electronic and paper mail.
 .
   If your software can interact with users remotely through a computer
 network, you should also make sure that it provides a way for users to
 get its source.  For example, if your program is a web application, its
 interface could display a "Source" link that leads users to an archive
 of the code.  There are many ways you could offer source, and different
 solutions will be better for different programs; see section 13 for the
 specific requirements.
 .
   You should also get your employer (if you work as a programmer) or school,
 if any, to sign a "copyright disclaimer" for the program, if necessary.
 For more information on this, and how to apply and follow the GNU AGPL, see
 <http://www.gnu.org/licenses/>.


================================================
FILE: debian/rules
================================================
#!/usr/bin/make -f
%:
	dh $@

override_dh_builddeb:
	dh_builddeb -- -Zgzip


================================================
FILE: debian/rustdesk-server-hbbr.install
================================================
bin/hbbr usr/bin
systemd/rustdesk-hbbr.service lib/systemd/system


================================================
FILE: debian/rustdesk-server-hbbr.postinst
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbr.service

if [ "$1" = "configure" ]; then
    mkdir -p /var/log/rustdesk-server
fi

case "$1" in
    configure|abort-upgrade|abort-deconfigure|abort-remove)
      mkdir -p /var/lib/rustdesk-server/
	  deb-systemd-helper unmask "${SERVICE}" >/dev/null || true
	  if deb-systemd-helper --quiet was-enabled "${SERVICE}"; then
	  	deb-systemd-invoke enable "${SERVICE}" >/dev/null || true
	  else
	  	deb-systemd-invoke update-state "${SERVICE}" >/dev/null || true
	  fi
	  systemctl --system daemon-reload >/dev/null || true
	  if [ -n "$2" ]; then
		deb-systemd-invoke restart "${SERVICE}" >/dev/null || true
	  else
		deb-systemd-invoke start "${SERVICE}" >/dev/null || true
	  fi
    ;;
esac

exit 0


================================================
FILE: debian/rustdesk-server-hbbr.postrm
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbr.service

systemctl --system daemon-reload >/dev/null || true

if [ "$1" = "purge" ]; then
	rm -rf /var/log/rustdesk-server/rustdesk-hbbr.*
	deb-systemd-helper purge "${SERVICE}" >/dev/null || true
	deb-systemd-helper unmask "${SERVICE}" >/dev/null || true
fi

if [ "$1" = "remove" ]; then
	deb-systemd-helper mask "${SERVICE}" >/dev/null || true
fi

exit 0


================================================
FILE: debian/rustdesk-server-hbbr.prerm
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbr.service

case "$1" in
    remove|deconfigure)
	  deb-systemd-invoke stop "${SERVICE}" >/dev/null || true
	  deb-systemd-invoke disable "${SERVICE}" >/dev/null || true
	;;
esac

exit 0


================================================
FILE: debian/rustdesk-server-hbbs.install
================================================
bin/hbbs usr/bin
systemd/rustdesk-hbbs.service lib/systemd/system


================================================
FILE: debian/rustdesk-server-hbbs.postinst
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbs.service

if [ "$1" = "configure" ]; then
    mkdir -p /var/log/rustdesk-server
fi

case "$1" in
    configure|abort-upgrade|abort-deconfigure|abort-remove)
      mkdir -p /var/lib/rustdesk-server/
	  deb-systemd-helper unmask "${SERVICE}" >/dev/null || true
	  if deb-systemd-helper --quiet was-enabled "${SERVICE}"; then
	  	deb-systemd-invoke enable "${SERVICE}" >/dev/null || true
	  else
	  	deb-systemd-invoke update-state "${SERVICE}" >/dev/null || true
	  fi
	  systemctl --system daemon-reload >/dev/null || true
	  if [ -n "$2" ]; then
		deb-systemd-invoke restart "${SERVICE}" >/dev/null || true
	  else
		deb-systemd-invoke start "${SERVICE}" >/dev/null || true
	  fi
    ;;
esac

exit 0


================================================
FILE: debian/rustdesk-server-hbbs.postrm
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbs.service

systemctl --system daemon-reload >/dev/null || true

if [ "$1" = "purge" ]; then
	rm -rf /var/lib/rustdesk-server/ /var/log/rustdesk-server/rustdesk-hbbs.*
	deb-systemd-helper purge "${SERVICE}" >/dev/null || true
	deb-systemd-helper unmask "${SERVICE}" >/dev/null || true
fi

if [ "$1" = "remove" ]; then
	deb-systemd-helper mask "${SERVICE}" >/dev/null || true
fi

exit 0


================================================
FILE: debian/rustdesk-server-hbbs.prerm
================================================
#!/bin/sh
set -e

SERVICE=rustdesk-hbbs.service

case "$1" in
    remove|deconfigure)
	  deb-systemd-invoke stop "${SERVICE}" >/dev/null || true
	  deb-systemd-invoke disable "${SERVICE}" >/dev/null || true
	;;
esac

exit 0


================================================
FILE: debian/rustdesk-server-utils.install
================================================
bin/rustdesk-utils usr/bin


================================================
FILE: debian/source/format
================================================
3.0 (native)


================================================
FILE: docker/Dockerfile
================================================
FROM busybox:stable

ARG S6_OVERLAY_VERSION=3.2.0.0
ARG S6_ARCH=x86_64
ADD https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz /tmp
ADD https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-${S6_ARCH}.tar.xz /tmp
RUN \
  tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz && \
  tar -C / -Jxpf /tmp/s6-overlay-${S6_ARCH}.tar.xz && \
  rm /tmp/s6-overlay*.tar.xz && \
  ln -s /run /var/run

COPY rootfs /

ENV RELAY=relay.example.com
ENV ENCRYPTED_ONLY=0

EXPOSE 21115 21116 21116/udp 21117 21118 21119

HEALTHCHECK --interval=10s --timeout=5s CMD /usr/bin/healthcheck.sh

WORKDIR /data

VOLUME /data

ENTRYPOINT ["/init"]


================================================
FILE: docker/healthcheck.sh
================================================
#!/bin/sh

/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbr || exit 1
/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbs || exit 1


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/dependencies
================================================
key-secret


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/run
================================================
#!/command/with-contenv sh
cd /data
PARAMS=
[ "${ENCRYPTED_ONLY}" = "1" ] && PARAMS="-k _"
/usr/bin/hbbr $PARAMS


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/type
================================================
longrun


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/dependencies
================================================
key-secret
hbbr


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/run
================================================
#!/command/with-contenv sh
sleep 2
cd /data
PARAMS=
[ "${ENCRYPTED_ONLY}" = "1" ] && PARAMS="-k _"
/usr/bin/hbbs -r $RELAY $PARAMS


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/type
================================================
longrun


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/type
================================================
oneshot


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up
================================================
/etc/s6-overlay/s6-rc.d/key-secret/up.real


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up.real
================================================
#!/command/with-contenv sh

if [ ! -d /data ] ; then
  mkdir /data
fi

# normal docker secrets
if [ ! -f /data/id_ed25519.pub ] && [ -r /run/secrets/key_pub ] ; then
  cp /run/secrets/key_pub /data/id_ed25519.pub
  echo "Public key created from secret"
fi

if [ ! -f /data/id_ed25519 ] && [ -r /run/secrets/key_priv ] ; then
  cp /run/secrets/key_priv /data/id_ed25519
  echo "Private key created from secret"
fi

# ENV variables
if [ ! -f /data/id_ed25519.pub ] && [ ! "$KEY_PUB" = "" ] ; then
  echo -n "$KEY_PUB" > /data/id_ed25519.pub
  echo "Public key created from ENV variable"
fi

if [ ! -f /data/id_ed25519 ] && [ ! "$KEY_PRIV" = "" ] ; then
  echo -n "$KEY_PRIV" > /data/id_ed25519
  echo "Private key created from ENV variable"
fi

# check if both keys provided
if [ -f /data/id_ed25519.pub ] && [ ! -f /data/id_ed25519 ] ; then
  echo "Private key missing."
  echo "You must provide BOTH the private and the public key."
  /run/s6/basedir/bin/halt
  exit 1
fi

if [ ! -f /data/id_ed25519.pub ] && [ -f /data/id_ed25519 ] ; then
  echo "Public key missing."
  echo "You must provide BOTH the private and the public key."
  /run/s6/basedir/bin/halt
  exit 1
fi

# here we have either no keys or both

# if we have both keys, we fix permissions and ownership
# and check for keypair validation
if [ -f /data/id_ed25519.pub ] && [ -f /data/id_ed25519 ] ; then
  chmod 0600 /data/id_ed25519.pub /data/id_ed25519
  chown root:root /data/id_ed25519.pub /data/id_ed25519
  /usr/bin/rustdesk-utils validatekeypair "$(cat /data/id_ed25519.pub)" "$(cat /data/id_ed25519)" || {
    echo "Key pair not valid"
    /run/s6/basedir/bin/halt
    exit 1
  }
fi

# if we have no keypair, hbbs will generate one


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbr
================================================


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbs
================================================


================================================
FILE: docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/key-secret
================================================


================================================
FILE: docker/rootfs/usr/bin/healthcheck.sh
================================================
#!/bin/sh

/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbr || exit 1
/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbs || exit 1


================================================
FILE: docker-classic/Dockerfile
================================================
FROM scratch
COPY hbbs /usr/bin/hbbs
COPY hbbr /usr/bin/hbbr
WORKDIR /root
ENV HOME=/root


================================================
FILE: docker-compose.yml
================================================
version: '3'

networks:
  rustdesk-net:
    external: false

services:
  hbbs:
    container_name: hbbs
    ports:
      - 21115:21115
      - 21116:21116
      - 21116:21116/udp
      - 21118:21118
    image: rustdesk/rustdesk-server:latest
    command: hbbs -r rustdesk.example.com:21117
    volumes:
      - ./data:/root
    networks:
      - rustdesk-net
    depends_on:
      - hbbr
    restart: unless-stopped

  hbbr:
    container_name: hbbr
    ports:
      - 21117:21117
      - 21119:21119
    image: rustdesk/rustdesk-server:latest
    command: hbbr
    volumes:
      - ./data:/root
    networks:
      - rustdesk-net
    restart: unless-stopped


================================================
FILE: kubernetes/example.yaml
================================================
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rustdesk-server
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: rustdesk
  template:
    metadata:
      labels:
        app: rustdesk
    spec:
      containers:
        # id Server (HBBS)
        - name: hbbs
          image: rustdesk/rustdesk-server:latest
          env:
            - name: RELAY_HOST
              value: "rustdesk.yourdomain.tld"
          command: ["hbbs", "-r", "$(RELAY_HOST):21117", "-k", "_"]
          volumeMounts:
            - mountPath: /root
              name: rustdesk-data
          ports:
            - containerPort: 21115
            - containerPort: 21116
              protocol: TCP
            - containerPort: 21116
              protocol: UDP
            - containerPort: 21118

        # Relay Server (HBBR)
        - name: hbbr
          image: rustdesk/rustdesk-server:latest
          command: ["hbbr", "-k", "_"]
          volumeMounts:
            - mountPath: /root
              name: rustdesk-data
          ports:
            - containerPort: 21117
            - containerPort: 21119

      volumes:
        - name: rustdesk-data
          persistentVolumeClaim:
            claimName: rustdesk-pvc
---
apiVersion: v1
kind: Service
metadata:
  name: rustdesk-service
spec:
  type: LoadBalancer # Or NodePort
  selector:
    app: rustdesk
  ports:
    - name: hbbs-tcp
      port: 21115
      targetPort: 21115
      protocol: TCP
    - name: hbbs-udp
      port: 21116
      targetPort: 21116
      protocol: UDP
    - name: hbbs-tcp-main
      port: 21116
      targetPort: 21116
      protocol: TCP
    - name: hbbr-tcp
      port: 21117
      targetPort: 21117
      protocol: TCP
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: rustdesk-pvc
spec:
  accessModes:
    - ReadWriteOnce # RWM would be available only with pro version
  resources:
    requests:
      storage: 1Gi


================================================
FILE: rcd/rustdesk-hbbr
================================================
#!/bin/sh

# PROVIDE: rustdesk_hbbr
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# rustdesk_hbbr_enable (bool):            Set to NO by default.
#               Set it to YES to enable rustdesk_hbbr.
# rustdesk_hbbr_args (string):            Set extra arguments to pass to rustdesk_hbbr
#               Default is "-k _".
# rustdesk_hbbr_user (string):            Set user that rustdesk_hbbr will run under
#               Default is "root".
# rustdesk_hbbr_group (string):           Set group that rustdesk_hbbr will run under
#               Default is "wheel".

. /etc/rc.subr

name=rustdesk_hbbr
desc="Rustdesk Relay Server"
rcvar=rustdesk_hbbr_enable

load_rc_config $name

: ${rustdesk_hbbr_enable:=NO}
: ${rustdesk_hbbr_args="-k _"}
: ${rustdesk_hbbr_user:=rustdesk}
: ${rustdesk_hbbr_group:=rustdesk}

pidfile=/var/run/rustdesk_hbbr.pid
command=/usr/sbin/daemon
procname=/usr/local/sbin/hbbr
rustdesk_hbbr_chdir=/var/db/rustdesk-server
command_args="-p ${pidfile} -o /var/log/rustdesk-hbbr.log ${procname} ${rustdesk_hbbr_args}"
## If you want the daemon do its log over syslog comment out the above line and remove the comment from the below replacement
#command_args="-p ${pidfile} -T ${name} ${procname} ${rustdesk_hbbr_args}"

start_precmd=rustdesk_hbbr_startprecmd

rustdesk_hbbr_startprecmd()
{
    if [ -e ${pidfile} ]; then
        chown ${rustdesk_hbbr_user}:${rustdesk_hbbr_group} ${pidfile};
    else
        install -o ${rustdesk_hbbr_user} -g ${rustdesk_hbbr_group} /dev/null ${pidfile};
    fi
    if [ -e ${rustdesk_hbbr_chdir} ]; then
        chown -R ${rustdesk_hbbr_user}:${rustdesk_hbbr_group} ${rustdesk_hbbr_chdir};
        chmod -R 770 ${rustdesk_hbbr_chdir};
    else
        mkdir -m 770 ${rustdesk_hbbr_chdir};
        chown ${rustdesk_hbbr_user}:${rustdesk_hbbr_group} ${rustdesk_hbbr_chdir};
    fi
    if [ -e /var/log/rustdesk-hbbr.log ]; then
        chown -R ${rustdesk_hbbr_user}:${rustdesk_hbbr_group} /var/log/rustdesk-hbbr.log;
        chmod 660 /var/log/rustdesk-hbbr.log;
    else
        install -o ${rustdesk_hbbr_user} -g ${rustdesk_hbbr_group} /dev/null /var/log/rustdesk-hbbr.log;
        chmod 660 /var/log/rustdesk-hbbr.log;
    fi
}

run_rc_command "$1"


================================================
FILE: rcd/rustdesk-hbbs
================================================
#!/bin/sh

# PROVIDE: rustdesk_hbbs
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# rustdesk_hbbs_enable (bool):            Set to NO by default.
#               Set it to YES to enable rustdesk_hbbs.
# rustdesk_hbbs_ip (string):              Set IP address/hostname of relay server to use
#               Defaults to "127.0.0.1", please replace with your server hostname/IP.
# rustdesk_hbbs_args (string):            Set extra arguments to pass to rustdesk_hbbs
#               Default is "-r ${rustdesk_hbbs_ip} -k _".
# rustdesk_hbbs_user (string):            Set user that rustdesk_hbbs will run under
#               Default is "root".
# rustdesk_hbbs_group (string):           Set group that rustdesk_hbbs will run under
#               Default is "wheel".

. /etc/rc.subr

name=rustdesk_hbbs
desc="Rustdesk ID/Rendezvous Server"
rcvar=rustdesk_hbbs_enable

load_rc_config $name

: ${rustdesk_hbbs_enable:=NO}
: ${rustdesk_hbbs_ip:=127.0.0.1}
: ${rustdesk_hbbs_args="-r ${rustdesk_hbbs_ip} -k _"}
: ${rustdesk_hbbs_user:=rustdesk}
: ${rustdesk_hbbs_group:=rustdesk}

pidfile=/var/run/rustdesk_hbbs.pid
command=/usr/sbin/daemon
procname=/usr/local/sbin/hbbs
rustdesk_hbbs_chdir=/var/db/rustdesk-server
command_args="-p ${pidfile} -o /var/log/rustdesk-hbbs.log ${procname} ${rustdesk_hbbs_args}"
## If you want the daemon to do its log over syslog, comment out the above line and remove the comment from the below replacement
#command_args="-p ${pidfile} -T ${name} ${procname} ${rustdesk_hbbs_args}"

start_precmd=rustdesk_hbbs_startprecmd

rustdesk_hbbs_startprecmd()
{
    if [ -e ${pidfile} ]; then
        chown ${rustdesk_hbbs_user}:${rustdesk_hbbs_group} ${pidfile};
    else
        install -o ${rustdesk_hbbs_user} -g ${rustdesk_hbbs_group} /dev/null ${pidfile};
    fi
    if [ -e ${rustdesk_hbbs_chdir} ]; then
        chown -R ${rustdesk_hbbs_user}:${rustdesk_hbbs_group} ${rustdesk_hbbs_chdir};
        chmod -R 770 ${rustdesk_hbbs_chdir};
    else
        mkdir -m 770 ${rustdesk_hbbs_chdir};
        chown ${rustdesk_hbbs_user}:${rustdesk_hbbs_group} ${rustdesk_hbbs_chdir};
    fi
    if [ -e /var/log/rustdesk-hbbs.log ]; then
        chown -R ${rustdesk_hbbs_user}:${rustdesk_hbbs_group} /var/log/rustdesk-hbbs.log;
        chmod 660 /var/log/rustdesk-hbbs.log;
    else
        install -o ${rustdesk_hbbs_user} -g ${rustdesk_hbbs_group} /dev/null /var/log/rustdesk-hbbs.log;
        chmod 660 /var/log/rustdesk-hbbs.log;
    fi
}

run_rc_command "$1"


================================================
FILE: src/common.rs
================================================
use clap::App;
use hbb_common::{
    allow_err, anyhow::{Context, Result}, get_version_number, log, tokio, ResultType
};
use ini::Ini;
use sodiumoxide::crypto::sign;
use std::{
    io::prelude::*,
    io::Read,
    net::SocketAddr,
    time::{Instant, SystemTime},
};

#[allow(dead_code)]
pub(crate) fn get_expired_time() -> Instant {
    let now = Instant::now();
    now.checked_sub(std::time::Duration::from_secs(3600))
        .unwrap_or(now)
}

#[allow(dead_code)]
pub(crate) fn test_if_valid_server(host: &str, name: &str) -> ResultType<SocketAddr> {
    use std::net::ToSocketAddrs;
    let res = if host.contains(':') {
        host.to_socket_addrs()?.next().context("")
    } else {
        format!("{}:{}", host, 0)
            .to_socket_addrs()?
            .next()
            .context("")
    };
    if res.is_err() {
        log::error!("Invalid {} {}: {:?}", name, host, res);
    }
    res
}

#[allow(dead_code)]
pub(crate) fn get_servers(s: &str, tag: &str) -> Vec<String> {
    let servers: Vec<String> = s
        .split(',')
        .filter(|x| !x.is_empty() && test_if_valid_server(x, tag).is_ok())
        .map(|x| x.to_owned())
        .collect();
    log::info!("{}={:?}", tag, servers);
    servers
}

#[allow(dead_code)]
#[inline]
fn arg_name(name: &str) -> String {
    name.to_uppercase().replace('_', "-")
}

#[allow(dead_code)]
pub fn init_args(args: &str, name: &str, about: &str) {
    let matches = App::new(name)
        .version(crate::version::VERSION)
        .author("Purslane Ltd. <info@rustdesk.com>")
        .about(about)
        .args_from_usage(args)
        .get_matches();
    if let Ok(v) = Ini::load_from_file(".env") {
        if let Some(section) = v.section(None::<String>) {
            section
                .iter()
                .for_each(|(k, v)| std::env::set_var(arg_name(k), v));
        }
    }
    if let Some(config) = matches.value_of("config") {
        if let Ok(v) = Ini::load_from_file(config) {
            if let Some(section) = v.section(None::<String>) {
                section
                    .iter()
                    .for_each(|(k, v)| std::env::set_var(arg_name(k), v));
            }
        }
    }
    for (k, v) in matches.args {
        if let Some(v) = v.vals.first() {
            std::env::set_var(arg_name(k), v.to_string_lossy().to_string());
        }
    }
}

#[allow(dead_code)]
#[inline]
pub fn get_arg(name: &str) -> String {
    get_arg_or(name, "".to_owned())
}

#[allow(dead_code)]
#[inline]
pub fn get_arg_or(name: &str, default: String) -> String {
    std::env::var(arg_name(name)).unwrap_or(default)
}

#[allow(dead_code)]
#[inline]
pub fn now() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|x| x.as_secs())
        .unwrap_or_default()
}

pub fn gen_sk(wait: u64) -> (String, Option<sign::SecretKey>) {
    let sk_file = "id_ed25519";
    if wait > 0 && !std::path::Path::new(sk_file).exists() {
        std::thread::sleep(std::time::Duration::from_millis(wait));
    }
    if let Ok(mut file) = std::fs::File::open(sk_file) {
        let mut contents = String::new();
        if file.read_to_string(&mut contents).is_ok() {
            let contents = contents.trim();
            let sk = base64::decode(contents).unwrap_or_default();
            if sk.len() == sign::SECRETKEYBYTES {
                let mut tmp = [0u8; sign::SECRETKEYBYTES];
                tmp[..].copy_from_slice(&sk);
                let pk = base64::encode(&tmp[sign::SECRETKEYBYTES / 2..]);
                log::info!("Private key comes from {}", sk_file);
                return (pk, Some(sign::SecretKey(tmp)));
            } else {
                // don't use log here, since it is async
                println!("Fatal error: malformed private key in {sk_file}.");
                std::process::exit(1);
            }
        }
    } else {
        let gen_func = || {
            let (tmp, sk) = sign::gen_keypair();
            (base64::encode(tmp), sk)
        };
        let (mut pk, mut sk) = gen_func();
        for _ in 0..300 {
            if !pk.contains('/') && !pk.contains(':') {
                break;
            }
            (pk, sk) = gen_func();
        }
        let pub_file = format!("{sk_file}.pub");
        if let Ok(mut f) = std::fs::File::create(&pub_file) {
            f.write_all(pk.as_bytes()).ok();
            if let Ok(mut f) = std::fs::File::create(sk_file) {
                let s = base64::encode(&sk);
                if f.write_all(s.as_bytes()).is_ok() {
                    log::info!("Private/public key written to {}/{}", sk_file, pub_file);
                    log::debug!("Public key: {}", pk);
                    return (pk, Some(sk));
                }
            }
        }
    }
    ("".to_owned(), None)
}

#[cfg(unix)]
pub async fn listen_signal() -> Result<()> {
    use hbb_common::tokio;
    use hbb_common::tokio::signal::unix::{signal, SignalKind};

    tokio::spawn(async {
        let mut s = signal(SignalKind::terminate())?;
        let terminate = s.recv();
        let mut s = signal(SignalKind::interrupt())?;
        let interrupt = s.recv();
        let mut s = signal(SignalKind::quit())?;
        let quit = s.recv();

        tokio::select! {
            _ = terminate => {
                log::info!("signal terminate");
            }
            _ = interrupt => {
                log::info!("signal interrupt");
            }
            _ = quit => {
                log::info!("signal quit");
            }
        }
        Ok(())
    })
    .await?
}

#[cfg(not(unix))]
pub async fn listen_signal() -> Result<()> {
    let () = std::future::pending().await;
    unreachable!();
}


pub fn check_software_update() {
    const ONE_DAY_IN_SECONDS: u64 = 60 * 60 * 24;
    std::thread::spawn(move || loop {
        std::thread::spawn(move || allow_err!(check_software_update_()));
        std::thread::sleep(std::time::Duration::from_secs(ONE_DAY_IN_SECONDS));
    });
}

#[tokio::main(flavor = "current_thread")]
async fn check_software_update_() -> hbb_common::ResultType<()> {
    let (request, url) = hbb_common::version_check_request(hbb_common::VER_TYPE_RUSTDESK_SERVER.to_string());
    let latest_release_response = reqwest::Client::builder().build()?
        .post(url)
        .json(&request)
        .send()
        .await?;

    let bytes = latest_release_response.bytes().await?;
    let resp: hbb_common::VersionCheckResponse = serde_json::from_slice(&bytes)?;
    let response_url = resp.url;
    let latest_release_version = response_url.rsplit('/').next().unwrap_or_default();
    if get_version_number(&latest_release_version) > get_version_number(crate::version::VERSION) {
       log::info!("new version is available: {}", latest_release_version);
    }
    Ok(())
}

================================================
FILE: src/database.rs
================================================
use async_trait::async_trait;
use hbb_common::{log, ResultType};
use sqlx::{
    sqlite::SqliteConnectOptions, ConnectOptions, Connection, Error as SqlxError, SqliteConnection,
};
use std::{ops::DerefMut, str::FromStr};
//use sqlx::postgres::PgPoolOptions;
//use sqlx::mysql::MySqlPoolOptions;

type Pool = deadpool::managed::Pool<DbPool>;

pub struct DbPool {
    url: String,
}

#[async_trait]
impl deadpool::managed::Manager for DbPool {
    type Type = SqliteConnection;
    type Error = SqlxError;
    async fn create(&self) -> Result<SqliteConnection, SqlxError> {
        let mut opt = SqliteConnectOptions::from_str(&self.url).unwrap();
        opt.log_statements(log::LevelFilter::Debug);
        SqliteConnection::connect_with(&opt).await
    }
    async fn recycle(
        &self,
        obj: &mut SqliteConnection,
    ) -> deadpool::managed::RecycleResult<SqlxError> {
        Ok(obj.ping().await?)
    }
}

#[derive(Clone)]
pub struct Database {
    pool: Pool,
}

#[derive(Default)]
pub struct Peer {
    pub guid: Vec<u8>,
    pub id: String,
    pub uuid: Vec<u8>,
    pub pk: Vec<u8>,
    pub user: Option<Vec<u8>>,
    pub info: String,
    pub status: Option<i64>,
}

impl Database {
    pub async fn new(url: &str) -> ResultType<Database> {
        if !std::path::Path::new(url).exists() {
            std::fs::File::create(url).ok();
        }
        let n: usize = std::env::var("MAX_DATABASE_CONNECTIONS")
            .unwrap_or_else(|_| "1".to_owned())
            .parse()
            .unwrap_or(1);
        log::debug!("MAX_DATABASE_CONNECTIONS={}", n);
        let pool = Pool::new(
            DbPool {
                url: url.to_owned(),
            },
            n,
        );
        let _ = pool.get().await?; // test
        let db = Database { pool };
        db.create_tables().await?;
        Ok(db)
    }

    async fn create_tables(&self) -> ResultType<()> {
        sqlx::query!(
            "
            create table if not exists peer (
                guid blob primary key not null,
                id varchar(100) not null,
                uuid blob not null,
                pk blob not null,
                created_at datetime not null default(current_timestamp),
                user blob,
                status tinyint,
                note varchar(300),
                info text not null
            ) without rowid;
            create unique index if not exists index_peer_id on peer (id);
            create index if not exists index_peer_user on peer (user);
            create index if not exists index_peer_created_at on peer (created_at);
            create index if not exists index_peer_status on peer (status);
        "
        )
        .execute(self.pool.get().await?.deref_mut())
        .await?;
        Ok(())
    }

    pub async fn get_peer(&self, id: &str) -> ResultType<Option<Peer>> {
        Ok(sqlx::query_as!(
            Peer,
            "select guid, id, uuid, pk, user, status, info from peer where id = ?",
            id
        )
        .fetch_optional(self.pool.get().await?.deref_mut())
        .await?)
    }

    pub async fn insert_peer(
        &self,
        id: &str,
        uuid: &[u8],
        pk: &[u8],
        info: &str,
    ) -> ResultType<Vec<u8>> {
        let guid = uuid::Uuid::new_v4().as_bytes().to_vec();
        sqlx::query!(
            "insert into peer(guid, id, uuid, pk, info) values(?, ?, ?, ?, ?)",
            guid,
            id,
            uuid,
            pk,
            info
        )
        .execute(self.pool.get().await?.deref_mut())
        .await?;
        Ok(guid)
    }

    pub async fn update_pk(
        &self,
        guid: &Vec<u8>,
        id: &str,
        pk: &[u8],
        info: &str,
    ) -> ResultType<()> {
        sqlx::query!(
            "update peer set id=?, pk=?, info=? where guid=?",
            id,
            pk,
            info,
            guid
        )
        .execute(self.pool.get().await?.deref_mut())
        .await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use hbb_common::tokio;
    #[test]
    fn test_insert() {
        insert();
    }

    #[tokio::main(flavor = "multi_thread")]
    async fn insert() {
        let db = super::Database::new("test.sqlite3").await.unwrap();
        let mut jobs = vec![];
        for i in 0..10000 {
            let cloned = db.clone();
            let id = i.to_string();
            let a = tokio::spawn(async move {
                let empty_vec = Vec::new();
                cloned
                    .insert_peer(&id, &empty_vec, &empty_vec, "")
                    .await
                    .unwrap();
            });
            jobs.push(a);
        }
        for i in 0..10000 {
            let cloned = db.clone();
            let id = i.to_string();
            let a = tokio::spawn(async move {
                cloned.get_peer(&id).await.unwrap();
            });
            jobs.push(a);
        }
        hbb_common::futures::future::join_all(jobs).await;
    }
}


================================================
FILE: src/hbbr.rs
================================================
use clap::App;
mod common;
mod relay_server;
use flexi_logger::*;
use hbb_common::{config::RELAY_PORT, ResultType};
use relay_server::*;
mod version;

fn main() -> ResultType<()> {
    let _logger = Logger::try_with_env_or_str("info")?
        .log_to_stdout()
        .format(opt_format)
        .write_mode(WriteMode::Async)
        .start()?;
    let args = format!(
        "-p, --port=[NUMBER(default={RELAY_PORT})] 'Sets the listening port'
        -k, --key=[KEY] 'Only allow the client with the same key'
        ",
    );
    let matches = App::new("hbbr")
        .version(version::VERSION)
        .author("Purslane Ltd. <info@rustdesk.com>")
        .about("RustDesk Relay Server")
        .args_from_usage(&args)
        .get_matches();
    if let Ok(v) = ini::Ini::load_from_file(".env") {
        if let Some(section) = v.section(None::<String>) {
            section.iter().for_each(|(k, v)| std::env::set_var(k, v));
        }
    }
    let mut port = RELAY_PORT;
    if let Ok(v) = std::env::var("PORT") {
        let v: i32 = v.parse().unwrap_or_default();
        if v > 0 {
            port = v + 1;
        }
    }
    start(
        matches.value_of("port").unwrap_or(&port.to_string()),
        matches
            .value_of("key")
            .unwrap_or(&std::env::var("KEY").unwrap_or_default()),
    )?;
    Ok(())
}


================================================
FILE: src/lib.rs
================================================
mod rendezvous_server;
pub use rendezvous_server::*;
pub mod common;
mod database;
mod peer;
mod version;


================================================
FILE: src/main.rs
================================================
// https://tools.ietf.org/rfc/rfc5128.txt
// https://blog.csdn.net/bytxl/article/details/44344855

use flexi_logger::*;
use hbb_common::{bail, config::RENDEZVOUS_PORT, ResultType};
use hbbs::{common::*, *};

const RMEM: usize = 0;

fn main() -> ResultType<()> {
    let _logger = Logger::try_with_env_or_str("info")?
        .log_to_stdout()
        .format(opt_format)
        .write_mode(WriteMode::Async)
        .start()?;
    let args = format!(
        "-c --config=[FILE] +takes_value 'Sets a custom config file'
        -p, --port=[NUMBER(default={RENDEZVOUS_PORT})] 'Sets the listening port'
        -s, --serial=[NUMBER(default=0)] 'Sets configure update serial number'
        -R, --rendezvous-servers=[HOSTS] 'Sets rendezvous servers, separated by comma'
        -u, --software-url=[URL] 'Sets download url of RustDesk software of newest version'
        -r, --relay-servers=[HOST] 'Sets the default relay servers, separated by comma'
        -M, --rmem=[NUMBER(default={RMEM})] 'Sets UDP recv buffer size, set system rmem_max first, e.g., sudo sysctl -w net.core.rmem_max=52428800. vi /etc/sysctl.conf, net.core.rmem_max=52428800, sudo sysctl –p'
        , --mask=[MASK] 'Determine if the connection comes from LAN, e.g. 192.168.0.0/16'
        -k, --key=[KEY] 'Only allow the client with the same key'",
    );
    init_args(&args, "hbbs", "RustDesk ID/Rendezvous Server");
    let port = get_arg_or("port", RENDEZVOUS_PORT.to_string()).parse::<i32>()?;
    if port < 3 {
        bail!("Invalid port");
    }
    let rmem = get_arg("rmem").parse::<usize>().unwrap_or(RMEM);
    let serial: i32 = get_arg("serial").parse().unwrap_or(0);
    crate::common::check_software_update();
    RendezvousServer::start(port, serial, &get_arg_or("key", "-".to_owned()), rmem)?;
    Ok(())
}


================================================
FILE: src/mod.rs
================================================
pub mod relay_server;
pub mod rendezvous_server;
mod sled_async;
use sled_async::*;


================================================
FILE: src/peer.rs
================================================
use crate::common::*;
use crate::database;
use hbb_common::{
    bytes::Bytes,
    log,
    rendezvous_proto::*,
    tokio::sync::{Mutex, RwLock},
    ResultType,
};
use serde_derive::{Deserialize, Serialize};
use std::{collections::HashMap, collections::HashSet, net::SocketAddr, sync::Arc, time::Instant};

type IpBlockMap = HashMap<String, ((u32, Instant), (HashSet<String>, Instant))>;
type UserStatusMap = HashMap<Vec<u8>, Arc<(Option<Vec<u8>>, bool)>>;
type IpChangesMap = HashMap<String, (Instant, HashMap<String, i32>)>;
lazy_static::lazy_static! {
    pub(crate) static ref IP_BLOCKER: Mutex<IpBlockMap> = Default::default();
    pub(crate) static ref USER_STATUS: RwLock<UserStatusMap> = Default::default();
    pub(crate) static ref IP_CHANGES: Mutex<IpChangesMap> = Default::default();
}
pub const IP_CHANGE_DUR: u64 = 180;
pub const IP_CHANGE_DUR_X2: u64 = IP_CHANGE_DUR * 2;
pub const DAY_SECONDS: u64 = 3600 * 24;
pub const IP_BLOCK_DUR: u64 = 60;

#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub(crate) struct PeerInfo {
    #[serde(default)]
    pub(crate) ip: String,
}

pub(crate) struct Peer {
    pub(crate) socket_addr: SocketAddr,
    pub(crate) last_reg_time: Instant,
    pub(crate) guid: Vec<u8>,
    pub(crate) uuid: Bytes,
    pub(crate) pk: Bytes,
    // pub(crate) user: Option<Vec<u8>>,
    pub(crate) info: PeerInfo,
    // pub(crate) disabled: bool,
    pub(crate) reg_pk: (u32, Instant), // how often register_pk
}

impl Default for Peer {
    fn default() -> Self {
        Self {
            socket_addr: "0.0.0.0:0".parse().unwrap(),
            last_reg_time: get_expired_time(),
            guid: Vec::new(),
            uuid: Bytes::new(),
            pk: Bytes::new(),
            info: Default::default(),
            // user: None,
            // disabled: false,
            reg_pk: (0, get_expired_time()),
        }
    }
}

pub(crate) type LockPeer = Arc<RwLock<Peer>>;

#[derive(Clone)]
pub(crate) struct PeerMap {
    map: Arc<RwLock<HashMap<String, LockPeer>>>,
    pub(crate) db: database::Database,
}

impl PeerMap {
    pub(crate) async fn new() -> ResultType<Self> {
        let db = std::env::var("DB_URL").unwrap_or({
            let mut db = "db_v2.sqlite3".to_owned();
            #[cfg(all(windows, not(debug_assertions)))]
            {
                if let Some(path) = hbb_common::config::Config::icon_path().parent() {
                    db = format!("{}\\{}", path.to_str().unwrap_or("."), db);
                }
            }
            #[cfg(not(windows))]
            {
                db = format!("./{db}");
            }
            db
        });
        log::info!("DB_URL={}", db);
        let pm = Self {
            map: Default::default(),
            db: database::Database::new(&db).await?,
        };
        Ok(pm)
    }

    #[inline]
    pub(crate) async fn update_pk(
        &mut self,
        id: String,
        peer: LockPeer,
        addr: SocketAddr,
        uuid: Bytes,
        pk: Bytes,
        ip: String,
    ) -> register_pk_response::Result {
        log::info!("update_pk {} {:?} {:?} {:?}", id, addr, uuid, pk);
        let (info_str, guid) = {
            let mut w = peer.write().await;
            w.socket_addr = addr;
            w.uuid = uuid.clone();
            w.pk = pk.clone();
            w.last_reg_time = Instant::now();
            w.info.ip = ip;
            (
                serde_json::to_string(&w.info).unwrap_or_default(),
                w.guid.clone(),
            )
        };
        if guid.is_empty() {
            match self.db.insert_peer(&id, &uuid, &pk, &info_str).await {
                Err(err) => {
                    log::error!("db.insert_peer failed: {}", err);
                    return register_pk_response::Result::SERVER_ERROR;
                }
                Ok(guid) => {
                    peer.write().await.guid = guid;
                }
            }
        } else {
            if let Err(err) = self.db.update_pk(&guid, &id, &pk, &info_str).await {
                log::error!("db.update_pk failed: {}", err);
                return register_pk_response::Result::SERVER_ERROR;
            }
            log::info!("pk updated instead of insert");
        }
        register_pk_response::Result::OK
    }

    #[inline]
    pub(crate) async fn get(&self, id: &str) -> Option<LockPeer> {
        let p = self.map.read().await.get(id).cloned();
        if p.is_some() {
            return p;
        } else if let Ok(Some(v)) = self.db.get_peer(id).await {
            let peer = Peer {
                guid: v.guid,
                uuid: v.uuid.into(),
                pk: v.pk.into(),
                // user: v.user,
                info: serde_json::from_str::<PeerInfo>(&v.info).unwrap_or_default(),
                // disabled: v.status == Some(0),
                ..Default::default()
            };
            let peer = Arc::new(RwLock::new(peer));
            self.map.write().await.insert(id.to_owned(), peer.clone());
            return Some(peer);
        }
        None
    }

    #[inline]
    pub(crate) async fn get_or(&self, id: &str) -> LockPeer {
        if let Some(p) = self.get(id).await {
            return p;
        }
        let mut w = self.map.write().await;
        if let Some(p) = w.get(id) {
            return p.clone();
        }
        let tmp = LockPeer::default();
        w.insert(id.to_owned(), tmp.clone());
        tmp
    }

    #[inline]
    pub(crate) async fn get_in_memory(&self, id: &str) -> Option<LockPeer> {
        self.map.read().await.get(id).cloned()
    }

    #[inline]
    pub(crate) async fn is_in_memory(&self, id: &str) -> bool {
        self.map.read().await.contains_key(id)
    }
}


================================================
FILE: src/relay_server.rs
================================================
use async_speed_limit::Limiter;
use async_trait::async_trait;
use hbb_common::{
    allow_err, bail,
    bytes::{Bytes, BytesMut},
    futures_util::{sink::SinkExt, stream::StreamExt},
    log,
    protobuf::Message as _,
    rendezvous_proto::*,
    sleep,
    tcp::{listen_any, FramedStream},
    timeout,
    tokio::{
        self,
        io::{AsyncReadExt, AsyncWriteExt},
        net::{TcpListener, TcpStream},
        sync::{Mutex, RwLock},
        time::{interval, Duration},
    },
    ResultType,
};
use sodiumoxide::crypto::sign;
use std::{
    collections::{HashMap, HashSet},
    io::prelude::*,
    io::Error,
    net::SocketAddr,
    sync::atomic::{AtomicUsize, Ordering},
};

type Usage = (usize, usize, usize, usize);

lazy_static::lazy_static! {
    static ref PEERS: Mutex<HashMap<String, Box<dyn StreamTrait>>> = Default::default();
    static ref USAGE: RwLock<HashMap<String, Usage>> = Default::default();
    static ref BLACKLIST: RwLock<HashSet<String>> = Default::default();
    static ref BLOCKLIST: RwLock<HashSet<String>> = Default::default();
}

static DOWNGRADE_THRESHOLD_100: AtomicUsize = AtomicUsize::new(66); // 0.66
static DOWNGRADE_START_CHECK: AtomicUsize = AtomicUsize::new(1_800_000); // in ms
static LIMIT_SPEED: AtomicUsize = AtomicUsize::new(32 * 1024 * 1024); // in bit/s
static TOTAL_BANDWIDTH: AtomicUsize = AtomicUsize::new(1024 * 1024 * 1024); // in bit/s
static SINGLE_BANDWIDTH: AtomicUsize = AtomicUsize::new(128 * 1024 * 1024); // in bit/s
const BLACKLIST_FILE: &str = "blacklist.txt";
const BLOCKLIST_FILE: &str = "blocklist.txt";

#[tokio::main(flavor = "multi_thread")]
pub async fn start(port: &str, key: &str) -> ResultType<()> {
    let key = get_server_sk(key);
    if let Ok(mut file) = std::fs::File::open(BLACKLIST_FILE) {
        let mut contents = String::new();
        if file.read_to_string(&mut contents).is_ok() {
            for x in contents.split('\n') {
                if let Some(ip) = x.trim().split(' ').next() {
                    BLACKLIST.write().await.insert(ip.to_owned());
                }
            }
        }
    }
    log::info!(
        "#blacklist({}): {}",
        BLACKLIST_FILE,
        BLACKLIST.read().await.len()
    );
    if let Ok(mut file) = std::fs::File::open(BLOCKLIST_FILE) {
        let mut contents = String::new();
        if file.read_to_string(&mut contents).is_ok() {
            for x in contents.split('\n') {
                if let Some(ip) = x.trim().split(' ').next() {
                    BLOCKLIST.write().await.insert(ip.to_owned());
                }
            }
        }
    }
    log::info!(
        "#blocklist({}): {}",
        BLOCKLIST_FILE,
        BLOCKLIST.read().await.len()
    );
    let port: u16 = port.parse()?;
    log::info!("Listening on tcp :{}", port);
    let port2 = port + 2;
    log::info!("Listening on websocket :{}", port2);
    let main_task = async move {
        loop {
            log::info!("Start");
            io_loop(listen_any(port).await?, listen_any(port2).await?, &key).await;
        }
    };
    let listen_signal = crate::common::listen_signal();
    tokio::select!(
        res = main_task => res,
        res = listen_signal => res,
    )
}

fn check_params() {
    let tmp = std::env::var("DOWNGRADE_THRESHOLD")
        .map(|x| x.parse::<f64>().unwrap_or(0.))
        .unwrap_or(0.);
    if tmp > 0. {
        DOWNGRADE_THRESHOLD_100.store((tmp * 100.) as _, Ordering::SeqCst);
    }
    log::info!(
        "DOWNGRADE_THRESHOLD: {}",
        DOWNGRADE_THRESHOLD_100.load(Ordering::SeqCst) as f64 / 100.
    );
    let tmp = std::env::var("DOWNGRADE_START_CHECK")
        .map(|x| x.parse::<usize>().unwrap_or(0))
        .unwrap_or(0);
    if tmp > 0 {
        DOWNGRADE_START_CHECK.store(tmp * 1000, Ordering::SeqCst);
    }
    log::info!(
        "DOWNGRADE_START_CHECK: {}s",
        DOWNGRADE_START_CHECK.load(Ordering::SeqCst) / 1000
    );
    let tmp = std::env::var("LIMIT_SPEED")
        .map(|x| x.parse::<f64>().unwrap_or(0.))
        .unwrap_or(0.);
    if tmp > 0. {
        LIMIT_SPEED.store((tmp * 1024. * 1024.) as usize, Ordering::SeqCst);
    }
    log::info!(
        "LIMIT_SPEED: {}Mb/s",
        LIMIT_SPEED.load(Ordering::SeqCst) as f64 / 1024. / 1024.
    );
    let tmp = std::env::var("TOTAL_BANDWIDTH")
        .map(|x| x.parse::<f64>().unwrap_or(0.))
        .unwrap_or(0.);
    if tmp > 0. {
        TOTAL_BANDWIDTH.store((tmp * 1024. * 1024.) as usize, Ordering::SeqCst);
    }

    log::info!(
        "TOTAL_BANDWIDTH: {}Mb/s",
        TOTAL_BANDWIDTH.load(Ordering::SeqCst) as f64 / 1024. / 1024.
    );
    let tmp = std::env::var("SINGLE_BANDWIDTH")
        .map(|x| x.parse::<f64>().unwrap_or(0.))
        .unwrap_or(0.);
    if tmp > 0. {
        SINGLE_BANDWIDTH.store((tmp * 1024. * 1024.) as usize, Ordering::SeqCst);
    }
    log::info!(
        "SINGLE_BANDWIDTH: {}Mb/s",
        SINGLE_BANDWIDTH.load(Ordering::SeqCst) as f64 / 1024. / 1024.
    )
}

async fn check_cmd(cmd: &str, limiter: Limiter) -> String {
    use std::fmt::Write;

    let mut res = "".to_owned();
    let mut fds = cmd.trim().split(' ');
    match fds.next() {
        Some("h") => {
            res = format!(
                "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n",
                "blacklist-add(ba) <ip>",
                "blacklist-remove(br) <ip>",
                "blacklist(b) <ip>",
                "blocklist-add(Ba) <ip>",
                "blocklist-remove(Br) <ip>",
                "blocklist(B) <ip>",
                "downgrade-threshold(dt) [value]",
                "downgrade-start-check(t) [value(second)]",
                "limit-speed(ls) [value(Mb/s)]",
                "total-bandwidth(tb) [value(Mb/s)]",
                "single-bandwidth(sb) [value(Mb/s)]",
                "usage(u)"
            )
        }
        Some("blacklist-add" | "ba") => {
            if let Some(ip) = fds.next() {
                for ip in ip.split('|') {
                    BLACKLIST.write().await.insert(ip.to_owned());
                }
            }
        }
        Some("blacklist-remove" | "br") => {
            if let Some(ip) = fds.next() {
                if ip == "all" {
                    BLACKLIST.write().await.clear();
                } else {
                    for ip in ip.split('|') {
                        BLACKLIST.write().await.remove(ip);
                    }
                }
            }
        }
        Some("blacklist" | "b") => {
            if let Some(ip) = fds.next() {
                res = format!("{}\n", BLACKLIST.read().await.get(ip).is_some());
            } else {
                for ip in BLACKLIST.read().await.clone().into_iter() {
                    let _ = writeln!(res, "{ip}");
                }
            }
        }
        Some("blocklist-add" | "Ba") => {
            if let Some(ip) = fds.next() {
                for ip in ip.split('|') {
                    BLOCKLIST.write().await.insert(ip.to_owned());
                }
            }
        }
        Some("blocklist-remove" | "Br") => {
            if let Some(ip) = fds.next() {
                if ip == "all" {
                    BLOCKLIST.write().await.clear();
                } else {
                    for ip in ip.split('|') {
                        BLOCKLIST.write().await.remove(ip);
                    }
                }
            }
        }
        Some("blocklist" | "B") => {
            if let Some(ip) = fds.next() {
                res = format!("{}\n", BLOCKLIST.read().await.get(ip).is_some());
            } else {
                for ip in BLOCKLIST.read().await.clone().into_iter() {
                    let _ = writeln!(res, "{ip}");
                }
            }
        }
        Some("downgrade-threshold" | "dt") => {
            if let Some(v) = fds.next() {
                if let Ok(v) = v.parse::<f64>() {
                    if v > 0. {
                        DOWNGRADE_THRESHOLD_100.store((v * 100.) as _, Ordering::SeqCst);
                    }
                }
            } else {
                res = format!(
                    "{}\n",
                    DOWNGRADE_THRESHOLD_100.load(Ordering::SeqCst) as f64 / 100.
                );
            }
        }
        Some("downgrade-start-check" | "t") => {
            if let Some(v) = fds.next() {
                if let Ok(v) = v.parse::<usize>() {
                    if v > 0 {
                        DOWNGRADE_START_CHECK.store(v * 1000, Ordering::SeqCst);
                    }
                }
            } else {
                res = format!("{}s\n", DOWNGRADE_START_CHECK.load(Ordering::SeqCst) / 1000);
            }
        }
        Some("limit-speed" | "ls") => {
            if let Some(v) = fds.next() {
                if let Ok(v) = v.parse::<f64>() {
                    if v > 0. {
                        LIMIT_SPEED.store((v * 1024. * 1024.) as _, Ordering::SeqCst);
                    }
                }
            } else {
                res = format!(
                    "{}Mb/s\n",
                    LIMIT_SPEED.load(Ordering::SeqCst) as f64 / 1024. / 1024.
                );
            }
        }
        Some("total-bandwidth" | "tb") => {
            if let Some(v) = fds.next() {
                if let Ok(v) = v.parse::<f64>() {
                    if v > 0. {
                        TOTAL_BANDWIDTH.store((v * 1024. * 1024.) as _, Ordering::SeqCst);
                        limiter.set_speed_limit(TOTAL_BANDWIDTH.load(Ordering::SeqCst) as _);
                    }
                }
            } else {
                res = format!(
                    "{}Mb/s\n",
                    TOTAL_BANDWIDTH.load(Ordering::SeqCst) as f64 / 1024. / 1024.
                );
            }
        }
        Some("single-bandwidth" | "sb") => {
            if let Some(v) = fds.next() {
                if let Ok(v) = v.parse::<f64>() {
                    if v > 0. {
                        SINGLE_BANDWIDTH.store((v * 1024. * 1024.) as _, Ordering::SeqCst);
                    }
                }
            } else {
                res = format!(
                    "{}Mb/s\n",
                    SINGLE_BANDWIDTH.load(Ordering::SeqCst) as f64 / 1024. / 1024.
                );
            }
        }
        Some("usage" | "u") => {
            let mut tmp: Vec<(String, Usage)> = USAGE
                .read()
                .await
                .iter()
                .map(|x| (x.0.clone(), *x.1))
                .collect();
            tmp.sort_by(|a, b| ((b.1).1).partial_cmp(&(a.1).1).unwrap());
            for (ip, (elapsed, total, highest, speed)) in tmp {
                if elapsed == 0 {
                    continue;
                }
                let _ = writeln!(
                    res,
                    "{}: {}s {:.2}MB {}kb/s {}kb/s {}kb/s",
                    ip,
                    elapsed / 1000,
                    total as f64 / 1024. / 1024. / 8.,
                    highest,
                    total / elapsed,
                    speed
                );
            }
        }
        _ => {}
    }
    res
}

async fn io_loop(listener: TcpListener, listener2: TcpListener, key: &str) {
    check_params();
    let limiter = <Limiter>::new(TOTAL_BANDWIDTH.load(Ordering::SeqCst) as _);
    loop {
        tokio::select! {
            res = listener.accept() => {
                match res {
                    Ok((stream, addr))  => {
                        stream.set_nodelay(true).ok();
                        handle_connection(stream, addr, &limiter, key, false).await;
                    }
                    Err(err) => {
                       log::error!("listener.accept failed: {}", err);
                       break;
                    }
                }
            }
            res = listener2.accept() => {
                match res {
                    Ok((stream, addr))  => {
                        stream.set_nodelay(true).ok();
                        handle_connection(stream, addr, &limiter, key, true).await;
                    }
                    Err(err) => {
                       log::error!("listener2.accept failed: {}", err);
                       break;
                    }
                }
            }
        }
    }
}

async fn handle_connection(
    stream: TcpStream,
    addr: SocketAddr,
    limiter: &Limiter,
    key: &str,
    ws: bool,
) {
    let ip = hbb_common::try_into_v4(addr).ip();
    if !ws && ip.is_loopback() {
        let limiter = limiter.clone();
        tokio::spawn(async move {
            let mut stream = stream;
            let mut buffer = [0; 1024];
            if let Ok(Ok(n)) = timeout(1000, stream.read(&mut buffer[..])).await {
                if let Ok(data) = std::str::from_utf8(&buffer[..n]) {
                    let res = check_cmd(data, limiter).await;
                    stream.write(res.as_bytes()).await.ok();
                }
            }
        });
        return;
    }
    let ip = ip.to_string();
    if BLOCKLIST.read().await.get(&ip).is_some() {
        log::info!("{} blocked", ip);
        return;
    }
    let key = key.to_owned();
    let limiter = limiter.clone();
    tokio::spawn(async move {
        allow_err!(make_pair(stream, addr, &key, limiter, ws).await);
    });
}

async fn make_pair(
    stream: TcpStream,
    mut addr: SocketAddr,
    key: &str,
    limiter: Limiter,
    ws: bool,
) -> ResultType<()> {
    if ws {
        use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
        let callback = |req: &Request, response: Response| {
            let headers = req.headers();
            let real_ip = headers
                .get("X-Real-IP")
                .or_else(|| headers.get("X-Forwarded-For"))
                .and_then(|header_value| header_value.to_str().ok());
            if let Some(ip) = real_ip {
                if ip.contains('.') {
                    addr = format!("{ip}:0").parse().unwrap_or(addr);
                } else {
                    addr = format!("[{ip}]:0").parse().unwrap_or(addr);
                }
            }
            Ok(response)
        };
        let ws_stream = tokio_tungstenite::accept_hdr_async(stream, callback).await?;
        make_pair_(ws_stream, addr, key, limiter).await;
    } else {
        make_pair_(FramedStream::from(stream, addr), addr, key, limiter).await;
    }
    Ok(())
}

async fn make_pair_(stream: impl StreamTrait, addr: SocketAddr, key: &str, limiter: Limiter) {
    let mut stream = stream;
    if let Ok(Some(Ok(bytes))) = timeout(30_000, stream.recv()).await {
        if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) {
            if let Some(rendezvous_message::Union::RequestRelay(rf)) = msg_in.union {
                if !key.is_empty() && rf.licence_key != key {
                    log::warn!("Relay authentication failed from {} - invalid key", addr);
                    return;
                }
                if !rf.uuid.is_empty() {
                    let mut peer = PEERS.lock().await.remove(&rf.uuid);
                    if let Some(peer) = peer.as_mut() {
                        log::info!("Relayrequest {} from {} got paired", rf.uuid, addr);
                        let id = format!("{}:{}", addr.ip(), addr.port());
                        USAGE.write().await.insert(id.clone(), Default::default());
                        if !stream.is_ws() && !peer.is_ws() {
                            peer.set_raw();
                            stream.set_raw();
                            log::info!("Both are raw");
                        }
                        if let Err(err) = relay(addr, &mut stream, peer, limiter, id.clone()).await
                        {
                            log::info!("Relay of {} closed: {}", addr, err);
                        } else {
                            log::info!("Relay of {} closed", addr);
                        }
                        USAGE.write().await.remove(&id);
                    } else {
                        log::info!("New relay request {} from {}", rf.uuid, addr);
                        PEERS.lock().await.insert(rf.uuid.clone(), Box::new(stream));
                        sleep(30.).await;
                        PEERS.lock().await.remove(&rf.uuid);
                    }
                }
            }
        }
    }
}

async fn relay(
    addr: SocketAddr,
    stream: &mut impl StreamTrait,
    peer: &mut Box<dyn StreamTrait>,
    total_limiter: Limiter,
    id: String,
) -> ResultType<()> {
    let ip = addr.ip().to_string();
    let mut tm = std::time::Instant::now();
    let mut elapsed = 0;
    let mut total = 0;
    let mut total_s = 0;
    let mut highest_s = 0;
    let mut downgrade: bool = false;
    let mut blacked: bool = false;
    let sb = SINGLE_BANDWIDTH.load(Ordering::SeqCst) as f64;
    let limiter = <Limiter>::new(sb);
    let blacklist_limiter = <Limiter>::new(LIMIT_SPEED.load(Ordering::SeqCst) as _);
    let downgrade_threshold =
        (sb * DOWNGRADE_THRESHOLD_100.load(Ordering::SeqCst) as f64 / 100. / 1000.) as usize; // in bit/ms
    let mut timer = interval(Duration::from_secs(3));
    let mut last_recv_time = std::time::Instant::now();
    loop {
        tokio::select! {
            res = peer.recv() => {
                if let Some(Ok(bytes)) = res {
                    last_recv_time = std::time::Instant::now();
                    let nb = bytes.len() * 8;
                    if blacked || downgrade {
                        blacklist_limiter.consume(nb).await;
                    } else {
                        limiter.consume(nb).await;
                    }
                    total_limiter.consume(nb).await;
                    total += nb;
                    total_s += nb;
                    if !bytes.is_empty() {
                        stream.send_raw(bytes.into()).await?;
                    }
                } else {
                    break;
                }
            },
            res = stream.recv() => {
                if let Some(Ok(bytes)) = res {
                    last_recv_time = std::time::Instant::now();
                    let nb = bytes.len() * 8;
                    if blacked || downgrade {
                        blacklist_limiter.consume(nb).await;
                    } else {
                        limiter.consume(nb).await;
                    }
                    total_limiter.consume(nb).await;
                    total += nb;
                    total_s += nb;
                    if !bytes.is_empty() {
                        peer.send_raw(bytes.into()).await?;
                    }
                } else {
                    break;
                }
            },
            _ = timer.tick() => {
                if last_recv_time.elapsed().as_secs() > 30 {
                    bail!("Timeout");
                }
            }
        }

        let n = tm.elapsed().as_millis() as usize;
        if n >= 1_000 {
            if BLOCKLIST.read().await.get(&ip).is_some() {
                log::info!("{} blocked", ip);
                break;
            }
            blacked = BLACKLIST.read().await.get(&ip).is_some();
            tm = std::time::Instant::now();
            let speed = total_s / n;
            if speed > highest_s {
                highest_s = speed;
            }
            elapsed += n;
            USAGE.write().await.insert(
                id.clone(),
                (elapsed as _, total as _, highest_s as _, speed as _),
            );
            total_s = 0;
            if elapsed > DOWNGRADE_START_CHECK.load(Ordering::SeqCst)
                && !downgrade
                && total > elapsed * downgrade_threshold
            {
                downgrade = true;
                log::info!(
                    "Downgrade {}, exceed downgrade threshold {}bit/ms in {}ms",
                    id,
                    downgrade_threshold,
                    elapsed
                );
            }
        }
    }
    Ok(())
}

fn get_server_sk(key: &str) -> String {
    let mut key = key.to_owned();
    if let Ok(sk) = base64::decode(&key) {
        if sk.len() == sign::SECRETKEYBYTES {
            log::info!("The key is a crypto private key");
            key = base64::encode(&sk[(sign::SECRETKEYBYTES / 2)..]);
        }
    }

    if key == "-" || key == "_" {
        let (pk, _) = crate::common::gen_sk(300);
        key = pk;
    }

    if !key.is_empty() {
        log::info!("Key: {}", key);
    }

    key
}

#[async_trait]
trait StreamTrait: Send + Sync + 'static {
    async fn recv(&mut self) -> Option<Result<BytesMut, Error>>;
    async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()>;
    fn is_ws(&self) -> bool;
    fn set_raw(&mut self);
}

#[async_trait]
impl StreamTrait for FramedStream {
    async fn recv(&mut self) -> Option<Result<BytesMut, Error>> {
        self.next().await
    }

    async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()> {
        self.send_bytes(bytes).await
    }

    fn is_ws(&self) -> bool {
        false
    }

    fn set_raw(&mut self) {
        self.set_raw();
    }
}

#[async_trait]
impl StreamTrait for tokio_tungstenite::WebSocketStream<TcpStream> {
    async fn recv(&mut self) -> Option<Result<BytesMut, Error>> {
        if let Some(msg) = self.next().await {
            match msg {
                Ok(msg) => {
                    match msg {
                        tungstenite::Message::Binary(bytes) => {
                            Some(Ok(bytes[..].into())) // to-do: poor performance
                        }
                        _ => Some(Ok(BytesMut::new())),
                    }
                }
                Err(err) => Some(Err(Error::new(std::io::ErrorKind::Other, err.to_string()))),
            }
        } else {
            None
        }
    }

    async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()> {
        Ok(self
            .send(tungstenite::Message::Binary(bytes.to_vec()))
            .await?) // to-do: poor performance
    }

    fn is_ws(&self) -> bool {
        true
    }

    fn set_raw(&mut self) {}
}


================================================
FILE: src/rendezvous_server.rs
================================================
use crate::common::*;
use crate::peer::*;
use hbb_common::{
    allow_err, bail,
    bytes::{Bytes, BytesMut},
    bytes_codec::BytesCodec,
    config,
    futures::future::join_all,
    futures_util::{
        sink::SinkExt,
        stream::{SplitSink, StreamExt},
    },
    log,
    protobuf::{Message as _, MessageField},
    rendezvous_proto::{
        register_pk_response::Result::{TOO_FREQUENT, UUID_MISMATCH},
        *,
    },
    tcp::{listen_any, FramedStream},
    timeout,
    tokio::{
        self,
        io::{AsyncReadExt, AsyncWriteExt},
        net::{TcpListener, TcpStream},
        sync::{mpsc, Mutex},
        time::{interval, Duration},
    },
    tokio_util::codec::Framed,
    try_into_v4,
    udp::FramedSocket,
    AddrMangle, ResultType,
};
use ipnetwork::Ipv4Network;
use sodiumoxide::crypto::sign;
use std::{
    collections::HashMap,
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
    sync::Arc,
    time::Instant,
};

#[derive(Clone, Debug)]
enum Data {
    Msg(Box<RendezvousMessage>, SocketAddr),
    RelayServers0(String),
    RelayServers(RelayServers),
}

const REG_TIMEOUT: i32 = 30_000;
type TcpStreamSink = SplitSink<Framed<TcpStream, BytesCodec>, Bytes>;
type WsSink = SplitSink<tokio_tungstenite::WebSocketStream<TcpStream>, tungstenite::Message>;
enum Sink {
    TcpStream(TcpStreamSink),
    Ws(WsSink),
}
type Sender = mpsc::UnboundedSender<Data>;
type Receiver = mpsc::UnboundedReceiver<Data>;
static ROTATION_RELAY_SERVER: AtomicUsize = AtomicUsize::new(0);
type RelayServers = Vec<String>;
const CHECK_RELAY_TIMEOUT: u64 = 3_000;
static ALWAYS_USE_RELAY: AtomicBool = AtomicBool::new(false);

// Store punch hole requests
use once_cell::sync::Lazy;
use tokio::sync::Mutex as TokioMutex; // differentiate if needed
#[derive(Clone)]
struct PunchReqEntry { tm: Instant, from_ip: String, to_ip: String, to_id: String }
static PUNCH_REQS: Lazy<TokioMutex<Vec<PunchReqEntry>>> = Lazy::new(|| TokioMutex::new(Vec::new()));
const PUNCH_REQ_DEDUPE_SEC: u64 = 60;

#[derive(Clone)]
struct Inner {
    serial: i32,
    version: String,
    software_url: String,
    mask: Option<Ipv4Network>,
    local_ip: String,
    sk: Option<sign::SecretKey>,
}

#[derive(Clone)]
pub struct RendezvousServer {
    tcp_punch: Arc<Mutex<HashMap<SocketAddr, Sink>>>,
    pm: PeerMap,
    tx: Sender,
    relay_servers: Arc<RelayServers>,
    relay_servers0: Arc<RelayServers>,
    rendezvous_servers: Arc<Vec<String>>,
    inner: Arc<Inner>,
}

enum LoopFailure {
    UdpSocket,
    Listener3,
    Listener2,
    Listener,
}

impl RendezvousServer {
    #[tokio::main(flavor = "multi_thread")]
    pub async fn start(port: i32, serial: i32, key: &str, rmem: usize) -> ResultType<()> {
        let (key, sk) = Self::get_server_sk(key);
        let nat_port = port - 1;
        let ws_port = port + 2;
        let pm = PeerMap::new().await?;
        log::info!("serial={}", serial);
        let rendezvous_servers = get_servers(&get_arg("rendezvous-servers"), "rendezvous-servers");
        log::info!("Listening on tcp/udp :{}", port);
        log::info!("Listening on tcp :{}, extra port for NAT test", nat_port);
        log::info!("Listening on websocket :{}", ws_port);
        let mut socket = create_udp_listener(port, rmem).await?;
        let (tx, mut rx) = mpsc::unbounded_channel::<Data>();
        let software_url = get_arg("software-url");
        let version = hbb_common::get_version_from_url(&software_url);
        if !version.is_empty() {
            log::info!("software_url: {}, version: {}", software_url, version);
        }
        let mask = get_arg("mask").parse().ok();
        let local_ip = if mask.is_none() {
            "".to_owned()
        } else {
            get_arg_or(
                "local-ip",
                local_ip_address::local_ip()
                    .map(|x| x.to_string())
                    .unwrap_or_default(),
            )
        };
        let mut rs = Self {
            tcp_punch: Arc::new(Mutex::new(HashMap::new())),
            pm,
            tx: tx.clone(),
            relay_servers: Default::default(),
            relay_servers0: Default::default(),
            rendezvous_servers: Arc::new(rendezvous_servers),
            inner: Arc::new(Inner {
                serial,
                version,
                software_url,
                sk,
                mask,
                local_ip,
            }),
        };
        log::info!("mask: {:?}", rs.inner.mask);
        log::info!("local-ip: {:?}", rs.inner.local_ip);
        std::env::set_var("PORT_FOR_API", port.to_string());
        rs.parse_relay_servers(&get_arg("relay-servers"));
        let mut listener = create_tcp_listener(port).await?;
        let mut listener2 = create_tcp_listener(nat_port).await?;
        let mut listener3 = create_tcp_listener(ws_port).await?;
        let test_addr = std::env::var("TEST_HBBS").unwrap_or_default();
        if std::env::var("ALWAYS_USE_RELAY")
            .unwrap_or_default()
            .to_uppercase()
            == "Y"
        {
            ALWAYS_USE_RELAY.store(true, Ordering::SeqCst);
        }
        log::info!(
            "ALWAYS_USE_RELAY={}",
            if ALWAYS_USE_RELAY.load(Ordering::SeqCst) {
                "Y"
            } else {
                "N"
            }
        );
        if test_addr.to_lowercase() != "no" {
            let test_addr = if test_addr.is_empty() {
                listener.local_addr()?
            } else {
                test_addr.parse()?
            };
            tokio::spawn(async move {
                if let Err(err) = test_hbbs(test_addr).await {
                    if test_addr.is_ipv6() && test_addr.ip().is_unspecified() {
                        let mut test_addr = test_addr;
                        test_addr.set_ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
                        if let Err(err) = test_hbbs(test_addr).await {
                            log::error!("Failed to run hbbs test with {test_addr}: {err}");
                            std::process::exit(1);
                        }
                    } else {
                        log::error!("Failed to run hbbs test with {test_addr}: {err}");
                        std::process::exit(1);
                    }
                }
            });
        };
        let main_task = async move {
            loop {
                log::info!("Start");
                match rs
                    .io_loop(
                        &mut rx,
                        &mut listener,
                        &mut listener2,
                        &mut listener3,
                        &mut socket,
                        &key,
                    )
                    .await
                {
                    LoopFailure::UdpSocket => {
                        drop(socket);
                        socket = create_udp_listener(port, rmem).await?;
                    }
                    LoopFailure::Listener => {
                        drop(listener);
                        listener = create_tcp_listener(port).await?;
                    }
                    LoopFailure::Listener2 => {
                        drop(listener2);
                        listener2 = create_tcp_listener(nat_port).await?;
                    }
                    LoopFailure::Listener3 => {
                        drop(listener3);
                        listener3 = create_tcp_listener(ws_port).await?;
                    }
                }
            }
        };
        let listen_signal = listen_signal();
        tokio::select!(
            res = main_task => res,
            res = listen_signal => res,
        )
    }

    async fn io_loop(
        &mut self,
        rx: &mut Receiver,
        listener: &mut TcpListener,
        listener2: &mut TcpListener,
        listener3: &mut TcpListener,
        socket: &mut FramedSocket,
        key: &str,
    ) -> LoopFailure {
        let mut timer_check_relay = interval(Duration::from_millis(CHECK_RELAY_TIMEOUT));
        loop {
            tokio::select! {
                _ = timer_check_relay.tick() => {
                    if self.relay_servers0.len() > 1 {
                        let rs = self.relay_servers0.clone();
                        let tx = self.tx.clone();
                        tokio::spawn(async move {
                            check_relay_servers(rs, tx).await;
                        });
                    }
                }
                Some(data) = rx.recv() => {
                    match data {
                        Data::Msg(msg, addr) => { allow_err!(socket.send(msg.as_ref(), addr).await); }
                        Data::RelayServers0(rs) => { self.parse_relay_servers(&rs); }
                        Data::RelayServers(rs) => { self.relay_servers = Arc::new(rs); }
                    }
                }
                res = socket.next() => {
                    match res {
                        Some(Ok((bytes, addr))) => {
                            if let Err(err) = self.handle_udp(&bytes, addr.into(), socket, key).await {
                                log::error!("udp failure: {}", err);
                                return LoopFailure::UdpSocket;
                            }
                        }
                        Some(Err(err)) => {
                            log::error!("udp failure: {}", err);
                            return LoopFailure::UdpSocket;
                        }
                        None => {
                            // unreachable!() ?
                        }
                    }
                }
                res = listener2.accept() => {
                    match res {
                        Ok((stream, addr))  => {
                            stream.set_nodelay(true).ok();
                            self.handle_listener2(stream, addr).await;
                        }
                        Err(err) => {
                           log::error!("listener2.accept failed: {}", err);
                           return LoopFailure::Listener2;
                        }
                    }
                }
                res = listener3.accept() => {
                    match res {
                        Ok((stream, addr))  => {
                            stream.set_nodelay(true).ok();
                            self.handle_listener(stream, addr, key, true).await;
                        }
                        Err(err) => {
                           log::error!("listener3.accept failed: {}", err);
                           return LoopFailure::Listener3;
                        }
                    }
                }
                res = listener.accept() => {
                    match res {
                        Ok((stream, addr)) => {
                            stream.set_nodelay(true).ok();
                            self.handle_listener(stream, addr, key, false).await;
                        }
                       Err(err) => {
                           log::error!("listener.accept failed: {}", err);
                           return LoopFailure::Listener;
                       }
                    }
                }
            }
        }
    }

    #[inline]
    async fn handle_udp(
        &mut self,
        bytes: &BytesMut,
        addr: SocketAddr,
        socket: &mut FramedSocket,
        key: &str,
    ) -> ResultType<()> {
        if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(bytes) {
            match msg_in.union {
                Some(rendezvous_message::Union::RegisterPeer(rp)) => {
                    // B registered
                    if !rp.id.is_empty() {
                        log::trace!("New peer registered: {:?} {:?}", &rp.id, &addr);
                        self.update_addr(rp.id, addr, socket).await?;
                        if self.inner.serial > rp.serial {
                            let mut msg_out = RendezvousMessage::new();
                            msg_out.set_configure_update(ConfigUpdate {
                                serial: self.inner.serial,
                                rendezvous_servers: (*self.rendezvous_servers).clone(),
                                ..Default::default()
                            });
                            socket.send(&msg_out, addr).await?;
                        }
                    }
                }
                Some(rendezvous_message::Union::RegisterPk(rk)) => {
                    if rk.uuid.is_empty() || rk.pk.is_empty() {
                        return Ok(());
                    }
                    let id = rk.id;
                    let ip = addr.ip().to_string();
                    if id.len() < 6 {
                        return send_rk_res(socket, addr, UUID_MISMATCH).await;
                    } else if !self.check_ip_blocker(&ip, &id).await {
                        return send_rk_res(socket, addr, TOO_FREQUENT).await;
                    }
                    let peer = self.pm.get_or(&id).await;
                    let (changed, ip_changed) = {
                        let peer = peer.read().await;
                        if peer.uuid.is_empty() {
                            (true, false)
                        } else {
                            if peer.uuid == rk.uuid {
                                if peer.info.ip != ip && peer.pk != rk.pk {
                                    log::warn!(
                                        "Peer {} ip/pk mismatch: {}/{:?} vs {}/{:?}",
                                        id,
                                        ip,
                                        rk.pk,
                                        peer.info.ip,
                                        peer.pk,
                                    );
                                    drop(peer);
                                    return send_rk_res(socket, addr, UUID_MISMATCH).await;
                                }
                            } else {
                                log::warn!(
                                    "Peer {} uuid mismatch: {:?} vs {:?}",
                                    id,
                                    rk.uuid,
                                    peer.uuid
                                );
                                drop(peer);
                                return send_rk_res(socket, addr, UUID_MISMATCH).await;
                            }
                            let ip_changed = peer.info.ip != ip;
                            (
                                peer.uuid != rk.uuid || peer.pk != rk.pk || ip_changed,
                                ip_changed,
                            )
                        }
                    };
                    let mut req_pk = peer.read().await.reg_pk;
                    if req_pk.1.elapsed().as_secs() > 6 {
                        req_pk.0 = 0;
                    } else if req_pk.0 > 2 {
                        return send_rk_res(socket, addr, TOO_FREQUENT).await;
                    }
                    req_pk.0 += 1;
                    req_pk.1 = Instant::now();
                    peer.write().await.reg_pk = req_pk;
                    if ip_changed {
                        let mut lock = IP_CHANGES.lock().await;
                        if let Some((tm, ips)) = lock.get_mut(&id) {
                            if tm.elapsed().as_secs() > IP_CHANGE_DUR {
                                *tm = Instant::now();
                                ips.clear();
                                ips.insert(ip.clone(), 1);
                            } else if let Some(v) = ips.get_mut(&ip) {
                                *v += 1;
                            } else {
                                ips.insert(ip.clone(), 1);
                            }
                        } else {
                            lock.insert(
                                id.clone(),
                                (Instant::now(), HashMap::from([(ip.clone(), 1)])),
                            );
                        }
                    }
                    if changed {
                        self.pm.update_pk(id, peer, addr, rk.uuid, rk.pk, ip).await;
                    }
                    let mut msg_out = RendezvousMessage::new();
                    msg_out.set_register_pk_response(RegisterPkResponse {
                        result: register_pk_response::Result::OK.into(),
                        ..Default::default()
                    });
                    socket.send(&msg_out, addr).await?
                }
                Some(rendezvous_message::Union::PunchHoleRequest(ph)) => {
                    if self.pm.is_in_memory(&ph.id).await {
                        self.handle_udp_punch_hole_request(addr, ph, key).await?;
                    } else {
                        // not in memory, fetch from db with spawn in case blocking me
                        let mut me = self.clone();
                        let key = key.to_owned();
                        tokio::spawn(async move {
                            allow_err!(me.handle_udp_punch_hole_request(addr, ph, &key).await);
                        });
                    }
                }
                Some(rendezvous_message::Union::PunchHoleSent(phs)) => {
                    self.handle_hole_sent(phs, addr, Some(socket)).await?;
                }
                Some(rendezvous_message::Union::LocalAddr(la)) => {
                    self.handle_local_addr(la, addr, Some(socket)).await?;
                }
                Some(rendezvous_message::Union::ConfigureUpdate(mut cu)) => {
                    if try_into_v4(addr).ip().is_loopback() && cu.serial > self.inner.serial {
                        let mut inner: Inner = (*self.inner).clone();
                        inner.serial = cu.serial;
                        self.inner = Arc::new(inner);
                        self.rendezvous_servers = Arc::new(
                            cu.rendezvous_servers
                                .drain(..)
                                .filter(|x| {
                                    !x.is_empty()
                                        && test_if_valid_server(x, "rendezvous-server").is_ok()
                                })
                                .collect(),
                        );
                        log::info!(
                            "configure updated: serial={} rendezvous-servers={:?}",
                            self.inner.serial,
                            self.rendezvous_servers
                        );
                    }
                }
                Some(rendezvous_message::Union::SoftwareUpdate(su)) => {
                    if !self.inner.version.is_empty() && su.url != self.inner.version {
                        let mut msg_out = RendezvousMessage::new();
                        msg_out.set_software_update(SoftwareUpdate {
                            url: self.inner.software_url.clone(),
                            ..Default::default()
                        });
                        socket.send(&msg_out, addr).await?;
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    #[inline]
    async fn handle_tcp(
        &mut self,
        bytes: &[u8],
        sink: &mut Option<Sink>,
        addr: SocketAddr,
        key: &str,
        ws: bool,
    ) -> bool {
        if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(bytes) {
            match msg_in.union {
                Some(rendezvous_message::Union::PunchHoleRequest(ph)) => {
                    // there maybe several attempt, so sink can be none
                    if let Some(sink) = sink.take() {
                        self.tcp_punch.lock().await.insert(try_into_v4(addr), sink);
                    }
                    allow_err!(self.handle_tcp_punch_hole_request(addr, ph, key, ws).await);
                    return true;
                }
                Some(rendezvous_message::Union::RequestRelay(mut rf)) => {
                    // there maybe several attempt, so sink can be none
                    if let Some(sink) = sink.take() {
                        self.tcp_punch.lock().await.insert(try_into_v4(addr), sink);
                    }
                    if let Some(peer) = self.pm.get_in_memory(&rf.id).await {
                        let mut msg_out = RendezvousMessage::new();
                        rf.socket_addr = AddrMangle::encode(addr).into();
                        msg_out.set_request_relay(rf);
                        let peer_addr = peer.read().await.socket_addr;
                        self.tx.send(Data::Msg(msg_out.into(), peer_addr)).ok();
                    }
                    return true;
                }
                Some(rendezvous_message::Union::RelayResponse(mut rr)) => {
                    let addr_b = AddrMangle::decode(&rr.socket_addr);
                    rr.socket_addr = Default::default();
                    let id = rr.id();
                    if !id.is_empty() {
                        let pk = self.get_pk(&rr.version, id.to_owned()).await;
                        rr.set_pk(pk);
                    }
                    let mut msg_out = RendezvousMessage::new();
                    if !rr.relay_server.is_empty() {
                        if self.is_lan(addr_b) {
                            // https://github.com/rustdesk/rustdesk-server/issues/24
                            rr.relay_server = self.inner.local_ip.clone();
                        } else if rr.relay_server == self.inner.local_ip {
                            rr.relay_server = self.get_relay_server(addr.ip(), addr_b.ip());
                        }
                    }
                    msg_out.set_relay_response(rr);
                    allow_err!(self.send_to_tcp_sync(msg_out, addr_b).await);
                }
                Some(rendezvous_message::Union::PunchHoleSent(phs)) => {
                    allow_err!(self.handle_hole_sent(phs, addr, None).await);
                }
                Some(rendezvous_message::Union::LocalAddr(la)) => {
                    allow_err!(self.handle_local_addr(la, addr, None).await);
                }
                Some(rendezvous_message::Union::TestNatRequest(tar)) => {
                    let mut msg_out = RendezvousMessage::new();
                    let mut res = TestNatResponse {
                        port: addr.port() as _,
                        ..Default::default()
                    };
                    if self.inner.serial > tar.serial {
                        let mut cu = ConfigUpdate::new();
                        cu.serial = self.inner.serial;
                        cu.rendezvous_servers = (*self.rendezvous_servers).clone();
                        res.cu = MessageField::from_option(Some(cu));
                    }
                    msg_out.set_test_nat_response(res);
                    Self::send_to_sink(sink, msg_out).await;
                }
                Some(rendezvous_message::Union::RegisterPk(_)) => {
                    let res = register_pk_response::Result::NOT_SUPPORT;
                    let mut msg_out = RendezvousMessage::new();
                    msg_out.set_register_pk_response(RegisterPkResponse {
                        result: res.into(),
                        ..Default::default()
                    });
                    Self::send_to_sink(sink, msg_out).await;
                }
                _ => {}
            }
        }
        false
    }

    #[inline]
    async fn update_addr(
        &mut self,
        id: String,
        socket_addr: SocketAddr,
        socket: &mut FramedSocket,
    ) -> ResultType<()> {
        let (request_pk, ip_change) = if let Some(old) = self.pm.get_in_memory(&id).await {
            let mut old = old.write().await;
            let ip = socket_addr.ip();
            let ip_change = if old.socket_addr.port() != 0 {
                ip != old.socket_addr.ip()
            } else {
                ip.to_string() != old.info.ip
            } && !ip.is_loopback();
            let request_pk = old.pk.is_empty() || ip_change;
            if !request_pk {
                old.socket_addr = socket_addr;
                old.last_reg_time = Instant::now();
            }
            let ip_change = if ip_change && old.reg_pk.0 <= 2 {
                Some(if old.socket_addr.port() == 0 {
                    old.info.ip.clone()
                } else {
                    old.socket_addr.to_string()
                })
            } else {
                None
            };
            (request_pk, ip_change)
        } else {
            (true, None)
        };
        if let Some(old) = ip_change {
            log::info!("IP change of {} from {} to {}", id, old, socket_addr);
        }
        let mut msg_out = RendezvousMessage::new();
        msg_out.set_register_peer_response(RegisterPeerResponse {
            request_pk,
            ..Default::default()
        });
        socket.send(&msg_out, socket_addr).await
    }

    #[inline]
    async fn handle_hole_sent<'a>(
        &mut self,
        phs: PunchHoleSent,
        addr: SocketAddr,
        socket: Option<&'a mut FramedSocket>,
    ) -> ResultType<()> {
        // punch hole sent from B, tell A that B is ready to be connected
        let addr_a = AddrMangle::decode(&phs.socket_addr);
        log::debug!(
            "{} punch hole response to {:?} from {:?}",
            if socket.is_none() { "TCP" } else { "UDP" },
            &addr_a,
            &addr
        );
        let mut msg_out = RendezvousMessage::new();
        let mut p = PunchHoleResponse {
            socket_addr: AddrMangle::encode(addr).into(),
            pk: self.get_pk(&phs.version, phs.id).await,
            relay_server: phs.relay_server.clone(),
            ..Default::default()
        };
        if let Ok(t) = phs.nat_type.enum_value() {
            p.set_nat_type(t);
        }
        msg_out.set_punch_hole_response(p);
        if let Some(socket) = socket {
            socket.send(&msg_out, addr_a).await?;
        } else {
            self.send_to_tcp(msg_out, addr_a).await;
        }
        Ok(())
    }

    #[inline]
    async fn handle_local_addr<'a>(
        &mut self,
        la: LocalAddr,
        addr: SocketAddr,
        socket: Option<&'a mut FramedSocket>,
    ) -> ResultType<()> {
        // relay local addrs of B to A
        let addr_a = AddrMangle::decode(&la.socket_addr);
        log::debug!(
            "{} local addrs response to {:?} from {:?}",
            if socket.is_none() { "TCP" } else { "UDP" },
            &addr_a,
            &addr
        );
        let mut msg_out = RendezvousMessage::new();
        let mut p = PunchHoleResponse {
            socket_addr: la.local_addr.clone(),
            pk: self.get_pk(&la.version, la.id).await,
            relay_server: la.relay_server,
            ..Default::default()
        };
        p.set_is_local(true);
        msg_out.set_punch_hole_response(p);
        if let Some(socket) = socket {
            socket.send(&msg_out, addr_a).await?;
        } else {
            self.send_to_tcp(msg_out, addr_a).await;
        }
        Ok(())
    }

    #[inline]
    async fn handle_punch_hole_request(
        &mut self,
        addr: SocketAddr,
        ph: PunchHoleRequest,
        key: &str,
        ws: bool,
    ) -> ResultType<(RendezvousMessage, Option<SocketAddr>)> {
        let mut ph = ph;
        if !key.is_empty() && ph.licence_key != key {
            log::warn!("Authentication failed from {} for peer {} - invalid key", addr, ph.id);
            let mut msg_out = RendezvousMessage::new();
            msg_out.set_punch_hole_response(PunchHoleResponse {
                failure: punch_hole_response::Failure::LICENSE_MISMATCH.into(),
                ..Default::default()
            });
            return Ok((msg_out, None));
        }
        let id = ph.id;
        // punch hole request from A, relay to B,
        // check if in same intranet first,
        // fetch local addrs if in same intranet.
        // because punch hole won't work if in the same intranet,
        // all routers will drop such self-connections.
        if let Some(peer) = self.pm.get(&id).await {
            let (elapsed, peer_addr) = {
                let r = peer.read().await;
                (r.last_reg_time.elapsed().as_millis() as i32, r.socket_addr)
            };
            if elapsed >= REG_TIMEOUT {
                let mut msg_out = RendezvousMessage::new();
                msg_out.set_punch_hole_response(PunchHoleResponse {
                    failure: punch_hole_response::Failure::OFFLINE.into(),
                    ..Default::default()
                });
                return Ok((msg_out, None));
            }
            
            // record punch hole request (from addr -> peer id/peer_addr)
            {
                let from_ip = try_into_v4(addr).ip().to_string();
                let to_ip = try_into_v4(peer_addr).ip().to_string();
                let to_id_clone = id.clone();
                let mut lock = PUNCH_REQS.lock().await;
                let mut dup = false;
                for e in lock.iter().rev().take(30) { // only check recent tail subset for speed
                    if e.from_ip == from_ip && e.to_id == to_id_clone {
                        if e.tm.elapsed().as_secs() < PUNCH_REQ_DEDUPE_SEC { dup = true; }
                        break;
                    }
                }
                if !dup { lock.push(PunchReqEntry { tm: Instant::now(), from_ip, to_ip, to_id: to_id_clone }); }
            }

            let mut msg_out = RendezvousMessage::new();
            let peer_is_lan = self.is_lan(peer_addr);
            let is_lan = self.is_lan(addr);
            let mut relay_server = self.get_relay_server(addr.ip(), peer_addr.ip());
            if ALWAYS_USE_RELAY.load(Ordering::SeqCst) || (peer_is_lan ^ is_lan) {
                if peer_is_lan {
                    // https://github.com/rustdesk/rustdesk-server/issues/24
                    relay_server = self.inner.local_ip.clone()
                }
                ph.nat_type = NatType::SYMMETRIC.into(); // will force relay
            }
            let same_intranet: bool = !ws
                && (peer_is_lan && is_lan || {
                    match (peer_addr, addr) {
                        (SocketAddr::V4(a), SocketAddr::V4(b)) => a.ip() == b.ip(),
                        (SocketAddr::V6(a), SocketAddr::V6(b)) => a.ip() == b.ip(),
                        _ => false,
                    }
                });
            let socket_addr = AddrMangle::encode(addr).into();
            if same_intranet {
                log::debug!(
                    "Fetch local addr {:?} {:?} request from {:?}",
                    id,
                    peer_addr,
                    addr
                );
                msg_out.set_fetch_local_addr(FetchLocalAddr {
                    socket_addr,
                    relay_server,
                    ..Default::default()
                });
            } else {
                log::debug!(
                    "Punch hole {:?} {:?} request from {:?}",
                    id,
                    peer_addr,
                    addr
                );
                msg_out.set_punch_hole(PunchHole {
                    socket_addr,
                    nat_type: ph.nat_type,
                    relay_server,
                    ..Default::default()
                });
            }
            Ok((msg_out, Some(peer_addr)))
        } else {
            let mut msg_out = RendezvousMessage::new();
            msg_out.set_punch_hole_response(PunchHoleResponse {
                failure: punch_hole_response::Failure::ID_NOT_EXIST.into(),
                ..Def
Download .txt
gitextract_n71cs4xt/

├── .cargo/
│   └── config.toml
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── dependabot.yml
│   └── workflows/
│       └── build.yaml
├── .gitignore
├── .gitmodules
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
├── debian/
│   ├── README.source
│   ├── changelog
│   ├── compat
│   ├── control.tpl
│   ├── copyright
│   ├── rules
│   ├── rustdesk-server-hbbr.install
│   ├── rustdesk-server-hbbr.postinst
│   ├── rustdesk-server-hbbr.postrm
│   ├── rustdesk-server-hbbr.prerm
│   ├── rustdesk-server-hbbs.install
│   ├── rustdesk-server-hbbs.postinst
│   ├── rustdesk-server-hbbs.postrm
│   ├── rustdesk-server-hbbs.prerm
│   ├── rustdesk-server-utils.install
│   └── source/
│       └── format
├── docker/
│   ├── Dockerfile
│   ├── healthcheck.sh
│   └── rootfs/
│       ├── etc/
│       │   └── s6-overlay/
│       │       └── s6-rc.d/
│       │           ├── hbbr/
│       │           │   ├── dependencies
│       │           │   ├── run
│       │           │   └── type
│       │           ├── hbbs/
│       │           │   ├── dependencies
│       │           │   ├── run
│       │           │   └── type
│       │           ├── key-secret/
│       │           │   ├── type
│       │           │   ├── up
│       │           │   └── up.real
│       │           └── user/
│       │               └── contents.d/
│       │                   ├── hbbr
│       │                   ├── hbbs
│       │                   └── key-secret
│       └── usr/
│           └── bin/
│               └── healthcheck.sh
├── docker-classic/
│   └── Dockerfile
├── docker-compose.yml
├── kubernetes/
│   └── example.yaml
├── rcd/
│   ├── rustdesk-hbbr
│   └── rustdesk-hbbs
├── src/
│   ├── common.rs
│   ├── database.rs
│   ├── hbbr.rs
│   ├── lib.rs
│   ├── main.rs
│   ├── mod.rs
│   ├── peer.rs
│   ├── relay_server.rs
│   ├── rendezvous_server.rs
│   └── utils.rs
├── systemd/
│   ├── rustdesk-hbbr.service
│   └── rustdesk-hbbs.service
└── ui/
    ├── .cargo/
    │   └── config.toml
    ├── .gitignore
    ├── Cargo.toml
    ├── build.rs
    ├── html/
    │   ├── .gitignore
    │   ├── index.html
    │   ├── main.js
    │   ├── package.json
    │   ├── style.css
    │   └── vite.config.js
    ├── icons/
    │   └── icon.icns
    ├── setup/
    │   └── service/
    │       └── run.cmd
    ├── setup.nsi
    ├── src/
    │   ├── adapter/
    │   │   ├── mod.rs
    │   │   ├── service/
    │   │   │   ├── mod.rs
    │   │   │   └── windows.rs
    │   │   └── view/
    │   │       ├── desktop.rs
    │   │       └── mod.rs
    │   ├── lib.rs
    │   ├── main.rs
    │   └── usecase/
    │       ├── mod.rs
    │       ├── presenter.rs
    │       ├── service.rs
    │       ├── view.rs
    │       └── watcher.rs
    └── tauri.conf.json
Download .txt
SYMBOL INDEX (166 symbols across 19 files)

FILE: build.rs
  function main (line 1) | fn main() {

FILE: src/common.rs
  function get_expired_time (line 15) | pub(crate) fn get_expired_time() -> Instant {
  function test_if_valid_server (line 22) | pub(crate) fn test_if_valid_server(host: &str, name: &str) -> ResultType...
  function get_servers (line 39) | pub(crate) fn get_servers(s: &str, tag: &str) -> Vec<String> {
  function arg_name (line 51) | fn arg_name(name: &str) -> String {
  function init_args (line 56) | pub fn init_args(args: &str, name: &str, about: &str) {
  function get_arg (line 88) | pub fn get_arg(name: &str) -> String {
  function get_arg_or (line 94) | pub fn get_arg_or(name: &str, default: String) -> String {
  function now (line 100) | pub fn now() -> u64 {
  function gen_sk (line 107) | pub fn gen_sk(wait: u64) -> (String, Option<sign::SecretKey>) {
  function listen_signal (line 158) | pub async fn listen_signal() -> Result<()> {
  function listen_signal (line 187) | pub async fn listen_signal() -> Result<()> {
  function check_software_update (line 193) | pub fn check_software_update() {
  function check_software_update_ (line 202) | async fn check_software_update_() -> hbb_common::ResultType<()> {

FILE: src/database.rs
  type Pool (line 10) | type Pool = deadpool::managed::Pool<DbPool>;
  type DbPool (line 12) | pub struct DbPool {
    type Type (line 18) | type Type = SqliteConnection;
    type Error (line 19) | type Error = SqlxError;
    method create (line 20) | async fn create(&self) -> Result<SqliteConnection, SqlxError> {
    method recycle (line 25) | async fn recycle(
  type Database (line 34) | pub struct Database {
    method new (line 50) | pub async fn new(url: &str) -> ResultType<Database> {
    method create_tables (line 71) | async fn create_tables(&self) -> ResultType<()> {
    method get_peer (line 96) | pub async fn get_peer(&self, id: &str) -> ResultType<Option<Peer>> {
    method insert_peer (line 106) | pub async fn insert_peer(
    method update_pk (line 127) | pub async fn update_pk(
  type Peer (line 39) | pub struct Peer {
  function test_insert (line 151) | fn test_insert() {
  function insert (line 156) | async fn insert() {

FILE: src/hbbr.rs
  function main (line 9) | fn main() -> ResultType<()> {

FILE: src/main.rs
  constant RMEM (line 8) | const RMEM: usize = 0;
  function main (line 10) | fn main() -> ResultType<()> {

FILE: src/peer.rs
  type IpBlockMap (line 13) | type IpBlockMap = HashMap<String, ((u32, Instant), (HashSet<String>, Ins...
  type UserStatusMap (line 14) | type UserStatusMap = HashMap<Vec<u8>, Arc<(Option<Vec<u8>>, bool)>>;
  type IpChangesMap (line 15) | type IpChangesMap = HashMap<String, (Instant, HashMap<String, i32>)>;
  constant IP_CHANGE_DUR (line 21) | pub const IP_CHANGE_DUR: u64 = 180;
  constant IP_CHANGE_DUR_X2 (line 22) | pub const IP_CHANGE_DUR_X2: u64 = IP_CHANGE_DUR * 2;
  constant DAY_SECONDS (line 23) | pub const DAY_SECONDS: u64 = 3600 * 24;
  constant IP_BLOCK_DUR (line 24) | pub const IP_BLOCK_DUR: u64 = 60;
  type PeerInfo (line 27) | pub(crate) struct PeerInfo {
  type Peer (line 32) | pub(crate) struct Peer {
  method default (line 45) | fn default() -> Self {
  type LockPeer (line 60) | pub(crate) type LockPeer = Arc<RwLock<Peer>>;
  type PeerMap (line 63) | pub(crate) struct PeerMap {
    method new (line 69) | pub(crate) async fn new() -> ResultType<Self> {
    method update_pk (line 93) | pub(crate) async fn update_pk(
    method get (line 136) | pub(crate) async fn get(&self, id: &str) -> Option<LockPeer> {
    method get_or (line 158) | pub(crate) async fn get_or(&self, id: &str) -> LockPeer {
    method get_in_memory (line 172) | pub(crate) async fn get_in_memory(&self, id: &str) -> Option<LockPeer> {
    method is_in_memory (line 177) | pub(crate) async fn is_in_memory(&self, id: &str) -> bool {

FILE: src/relay_server.rs
  type Usage (line 31) | type Usage = (usize, usize, usize, usize);
  constant BLACKLIST_FILE (line 45) | const BLACKLIST_FILE: &str = "blacklist.txt";
  constant BLOCKLIST_FILE (line 46) | const BLOCKLIST_FILE: &str = "blocklist.txt";
  function start (line 49) | pub async fn start(port: &str, key: &str) -> ResultType<()> {
  function check_params (line 98) | fn check_params() {
  function check_cmd (line 152) | async fn check_cmd(cmd: &str, limiter: Limiter) -> String {
  function io_loop (line 326) | async fn io_loop(listener: TcpListener, listener2: TcpListener, key: &st...
  function handle_connection (line 359) | async fn handle_connection(
  function make_pair (line 393) | async fn make_pair(
  function make_pair_ (line 425) | async fn make_pair_(stream: impl StreamTrait, addr: SocketAddr, key: &st...
  function relay (line 464) | async fn relay(
  function get_server_sk (line 568) | fn get_server_sk(key: &str) -> String {
  type StreamTrait (line 590) | trait StreamTrait: Send + Sync + 'static {
    method recv (line 591) | async fn recv(&mut self) -> Option<Result<BytesMut, Error>>;
    method send_raw (line 592) | async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()>;
    method is_ws (line 593) | fn is_ws(&self) -> bool;
    method set_raw (line 594) | fn set_raw(&mut self);
    method recv (line 599) | async fn recv(&mut self) -> Option<Result<BytesMut, Error>> {
    method send_raw (line 603) | async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()> {
    method is_ws (line 607) | fn is_ws(&self) -> bool {
    method set_raw (line 611) | fn set_raw(&mut self) {
    method recv (line 618) | async fn recv(&mut self) -> Option<Result<BytesMut, Error>> {
    method send_raw (line 636) | async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()> {
    method is_ws (line 642) | fn is_ws(&self) -> bool {
    method set_raw (line 646) | fn set_raw(&mut self) {}

FILE: src/rendezvous_server.rs
  type Data (line 44) | enum Data {
  constant REG_TIMEOUT (line 50) | const REG_TIMEOUT: i32 = 30_000;
  type TcpStreamSink (line 51) | type TcpStreamSink = SplitSink<Framed<TcpStream, BytesCodec>, Bytes>;
  type WsSink (line 52) | type WsSink = SplitSink<tokio_tungstenite::WebSocketStream<TcpStream>, t...
  type Sink (line 53) | enum Sink {
  type Sender (line 57) | type Sender = mpsc::UnboundedSender<Data>;
  type Receiver (line 58) | type Receiver = mpsc::UnboundedReceiver<Data>;
  type RelayServers (line 60) | type RelayServers = Vec<String>;
  constant CHECK_RELAY_TIMEOUT (line 61) | const CHECK_RELAY_TIMEOUT: u64 = 3_000;
  type PunchReqEntry (line 68) | struct PunchReqEntry { tm: Instant, from_ip: String, to_ip: String, to_i...
  constant PUNCH_REQ_DEDUPE_SEC (line 70) | const PUNCH_REQ_DEDUPE_SEC: u64 = 60;
  type Inner (line 73) | struct Inner {
  type RendezvousServer (line 83) | pub struct RendezvousServer {
    method start (line 102) | pub async fn start(port: i32, serial: i32, key: &str, rmem: usize) -> ...
    method io_loop (line 231) | async fn io_loop(
    method handle_udp (line 317) | async fn handle_udp(
    method handle_tcp (line 483) | async fn handle_tcp(
    method update_addr (line 572) | async fn update_addr(
    method handle_hole_sent (line 616) | async fn handle_hole_sent<'a>(
    method handle_local_addr (line 650) | async fn handle_local_addr<'a>(
    method handle_punch_hole_request (line 682) | async fn handle_punch_hole_request(
    method handle_online_request (line 793) | async fn handle_online_request(
    method send_to_tcp (line 822) | async fn send_to_tcp(&mut self, msg: RendezvousMessage, addr: SocketAd...
    method send_to_sink (line 830) | async fn send_to_sink(sink: &mut Option<Sink>, msg: RendezvousMessage) {
    method send_to_tcp_sync (line 846) | async fn send_to_tcp_sync(
    method handle_tcp_punch_hole_request (line 857) | async fn handle_tcp_punch_hole_request(
    method handle_udp_punch_hole_request (line 874) | async fn handle_udp_punch_hole_request(
    method check_ip_blocker (line 891) | async fn check_ip_blocker(&self, ip: &str, id: &str) -> bool {
    method parse_relay_servers (line 921) | fn parse_relay_servers(&mut self, relay_servers: &str) {
    method get_relay_server (line 927) | fn get_relay_server(&self, _pa: IpAddr, _pb: IpAddr) -> String {
    method check_cmd (line 937) | async fn check_cmd(&self, cmd: &str) -> String {
    method handle_listener2 (line 1102) | async fn handle_listener2(&self, stream: TcpStream, addr: SocketAddr) {
    method handle_listener (line 1142) | async fn handle_listener(&self, stream: TcpStream, addr: SocketAddr, k...
    method handle_listener_inner (line 1152) | async fn handle_listener_inner(
    method get_pk (line 1204) | async fn get_pk(&mut self, version: &str, id: String) -> Bytes {
    method get_server_sk (line 1229) | fn get_server_sk(key: &str) -> (String, Option<sign::SecretKey>) {
    method is_lan (line 1257) | fn is_lan(&self, addr: SocketAddr) -> bool {
  type LoopFailure (line 93) | enum LoopFailure {
  function check_relay_servers (line 1275) | async fn check_relay_servers(rs0: Arc<RelayServers>, tx: Sender) {
  function test_hbbs (line 1303) | async fn test_hbbs(addr: SocketAddr) -> ResultType<()> {
  function send_rk_res (line 1341) | async fn send_rk_res(
  function create_udp_listener (line 1354) | async fn create_udp_listener(port: i32, rmem: usize) -> ResultType<Frame...
  function create_tcp_listener (line 1367) | async fn create_tcp_listener(port: i32) -> ResultType<TcpListener> {

FILE: src/utils.rs
  function print_help (line 10) | fn print_help() {
  function error_then_help (line 22) | fn error_then_help(msg: &str) {
  function gen_keypair (line 27) | fn gen_keypair() {
  function validate_keypair (line 35) | fn validate_keypair(pk: &str, sk: &str) -> ResultType<()> {
  function doctor_tcp (line 75) | fn doctor_tcp(address: std::net::IpAddr, port: &str, desc: &str) {
  function doctor_ip (line 91) | fn doctor_ip(server_ip_address: std::net::IpAddr, server_address: Option...
  function doctor (line 122) | fn doctor(server_address_unclean: &str) {
  function main (line 142) | fn main() {

FILE: ui/build.rs
  function main (line 1) | fn main() {

FILE: ui/html/main.js
  class View (line 8) | class View {
    method constructor (line 9) | constructor() {
    method init (line 21) | async init() {
    method update (line 40) | async update() {
    method editorSave (line 64) | async editorSave(editor, e) {
    method editorScroll (line 80) | editorScroll(e) {
    method formChange (line 89) | formChange(e) {
    method appAction (line 96) | appAction(e) {
    method render (line 113) | render() {
    method renderForm (line 126) | renderForm() {
    method renderEditor (line 140) | renderEditor() {
    method renderScrollbar (line 153) | renderScrollbar() {

FILE: ui/src/adapter/service/windows.rs
  type WindowsDesktopService (line 11) | pub struct WindowsDesktopService {
  method start (line 17) | fn start(&mut self) {
  method stop (line 37) | fn stop(&mut self) {
  method restart (line 53) | fn restart(&mut self) {
  method pause (line 58) | fn pause(&mut self) {
  method check (line 72) | fn check(&mut self) -> DesktopServiceState {
  function call (line 82) | fn call(cmd: String) {
  function exec (line 95) | fn exec<I, S>(program: S, args: I) -> String
  function nssm (line 106) | fn nssm<I>(args: I) -> String
  function service_status (line 119) | fn service_status(name: &str) -> String {

FILE: ui/src/adapter/view/desktop.rs
  function run (line 18) | pub async fn run(sender: Sender<Event>, receiver: Receiver<Event>) {
  function root (line 219) | fn root() -> String {

FILE: ui/src/lib.rs
  function path (line 10) | pub fn path() -> PathBuf {

FILE: ui/src/main.rs
  function main (line 17) | async fn main() {

FILE: ui/src/usecase/presenter.rs
  function create (line 8) | pub async fn create(sender: Sender<Event>, receiver: Receiver<Event>) {

FILE: ui/src/usecase/service.rs
  function create (line 3) | pub fn create() -> Option<Box<dyn IDesktopService + Send>> {
  type DesktopServiceState (line 11) | pub enum DesktopServiceState {
  type IDesktopService (line 18) | pub trait IDesktopService {
    method start (line 19) | fn start(&mut self);
    method stop (line 20) | fn stop(&mut self);
    method restart (line 21) | fn restart(&mut self);
    method pause (line 22) | fn pause(&mut self);
    method check (line 23) | fn check(&mut self) -> DesktopServiceState;

FILE: ui/src/usecase/view.rs
  function create (line 5) | pub async fn create(sender: Sender<Event>, receiver: Receiver<Event>) {
  type Event (line 10) | pub enum Event {

FILE: ui/src/usecase/watcher.rs
  function create (line 9) | pub async fn create(sender: Sender<Event>) {
  function watch (line 27) | fn watch<P: AsRef<Path>>(path: P, sender: Sender<Event>) -> Result<()> {
Condensed preview — 87 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (270K chars).
[
  {
    "path": ".cargo/config.toml",
    "chars": 278,
    "preview": "[target.x86_64-pc-windows-msvc]\nrustflags = [\"-Ctarget-feature=+crt-static\"]\n[target.i686-pc-windows-msvc]\nrustflags = ["
  },
  {
    "path": ".gitattributes",
    "chars": 12,
    "preview": "* text=auto\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 1026,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: 'bug'\nassignees: ''\n\n---\n\n**Describe th"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 28,
    "preview": "blank_issues_enabled: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 774,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: 'enhancement'\nassignees: ''\n\n---\n\n**"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 228,
    "preview": "version: 2\nupdates:\n  - package-ecosystem: \"gitsubmodule\"\n    directory: \"/\"\n    target-branch: \"master\"\n    schedule:\n "
  },
  {
    "path": ".github/workflows/build.yaml",
    "chars": 22003,
    "preview": "name: build\n\n# ------------- NOTE\n# please setup some secrets before running this workflow:\n# DOCKER_IMAGE should be the"
  },
  {
    "path": ".gitignore",
    "chars": 135,
    "preview": "target\nid*\ndb*\ndebian-build\ndebian/.debhelper\ndebian/debhelper-build-stamp\n.DS_Store\n.vscode\nsrc/version.rs\ndb_v2.sqlite"
  },
  {
    "path": ".gitmodules",
    "chars": 100,
    "preview": "[submodule \"libs/hbb_common\"]\n\tpath = libs/hbb_common\n\turl = https://github.com/rustdesk/hbb_common\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 2431,
    "preview": "[package]\nname = \"hbbs\"\nversion = \"1.1.15\"\nauthors = [\"rustdesk <info@rustdesk.com>\"]\nedition = \"2021\"\nbuild = \"build.rs"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 1303,
    "preview": "# RustDesk Server Program\n\n[![build](https://github.com/rustdesk/rustdesk-server/actions/workflows/build.yaml/badge.svg)"
  },
  {
    "path": "build.rs",
    "chars": 45,
    "preview": "fn main() {\n    hbb_common::gen_version();\n}\n"
  },
  {
    "path": "debian/README.source",
    "chars": 1526,
    "preview": "#\n# Juli Augustus 2025 was building the downloadable Debian packages done\n# by github.com CI, meaning you being depended"
  },
  {
    "path": "debian/changelog",
    "chars": 2213,
    "preview": "rustdesk-server (1.1.15) UNRELEASED; urgency=medium\n\n  * Fix: 127.0.0.1 is not loopback (#515)\n  * Higher default bandwi"
  },
  {
    "path": "debian/compat",
    "chars": 3,
    "preview": "10\n"
  },
  {
    "path": "debian/control.tpl",
    "chars": 843,
    "preview": "Source: rustdesk-server\nSection: net\nPriority: optional\nMaintainer: open-trade <info@rustdesk.com>\nBuild-Depends: debhel"
  },
  {
    "path": "debian/copyright",
    "chars": 36138,
    "preview": "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: rustdesk-server\nFiles: *\nCopyr"
  },
  {
    "path": "debian/rules",
    "chars": 75,
    "preview": "#!/usr/bin/make -f\n%:\n\tdh $@\n\noverride_dh_builddeb:\n\tdh_builddeb -- -Zgzip\n"
  },
  {
    "path": "debian/rustdesk-server-hbbr.install",
    "chars": 66,
    "preview": "bin/hbbr usr/bin\nsystemd/rustdesk-hbbr.service lib/systemd/system\n"
  },
  {
    "path": "debian/rustdesk-server-hbbr.postinst",
    "chars": 739,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbr.service\n\nif [ \"$1\" = \"configure\" ]; then\n    mkdir -p /var/log/rustdesk-server\nf"
  },
  {
    "path": "debian/rustdesk-server-hbbr.postrm",
    "chars": 397,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbr.service\n\nsystemctl --system daemon-reload >/dev/null || true\n\nif [ \"$1\" = \"purge"
  },
  {
    "path": "debian/rustdesk-server-hbbr.prerm",
    "chars": 224,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbr.service\n\ncase \"$1\" in\n    remove|deconfigure)\n\t  deb-systemd-invoke stop \"${SERV"
  },
  {
    "path": "debian/rustdesk-server-hbbs.install",
    "chars": 66,
    "preview": "bin/hbbs usr/bin\nsystemd/rustdesk-hbbs.service lib/systemd/system\n"
  },
  {
    "path": "debian/rustdesk-server-hbbs.postinst",
    "chars": 739,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbs.service\n\nif [ \"$1\" = \"configure\" ]; then\n    mkdir -p /var/log/rustdesk-server\nf"
  },
  {
    "path": "debian/rustdesk-server-hbbs.postrm",
    "chars": 423,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbs.service\n\nsystemctl --system daemon-reload >/dev/null || true\n\nif [ \"$1\" = \"purge"
  },
  {
    "path": "debian/rustdesk-server-hbbs.prerm",
    "chars": 224,
    "preview": "#!/bin/sh\nset -e\n\nSERVICE=rustdesk-hbbs.service\n\ncase \"$1\" in\n    remove|deconfigure)\n\t  deb-systemd-invoke stop \"${SERV"
  },
  {
    "path": "debian/rustdesk-server-utils.install",
    "chars": 27,
    "preview": "bin/rustdesk-utils usr/bin\n"
  },
  {
    "path": "debian/source/format",
    "chars": 13,
    "preview": "3.0 (native)\n"
  },
  {
    "path": "docker/Dockerfile",
    "chars": 720,
    "preview": "FROM busybox:stable\n\nARG S6_OVERLAY_VERSION=3.2.0.0\nARG S6_ARCH=x86_64\nADD https://github.com/just-containers/s6-overlay"
  },
  {
    "path": "docker/healthcheck.sh",
    "chars": 159,
    "preview": "#!/bin/sh\n\n/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbr || exit 1\n/package/admin/s6/command/s6-svstat"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/dependencies",
    "chars": 11,
    "preview": "key-secret\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/run",
    "chars": 113,
    "preview": "#!/command/with-contenv sh\ncd /data\nPARAMS=\n[ \"${ENCRYPTED_ONLY}\" = \"1\" ] && PARAMS=\"-k _\"\n/usr/bin/hbbr $PARAMS\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/type",
    "chars": 8,
    "preview": "longrun\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/dependencies",
    "chars": 16,
    "preview": "key-secret\nhbbr\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/run",
    "chars": 131,
    "preview": "#!/command/with-contenv sh\nsleep 2\ncd /data\nPARAMS=\n[ \"${ENCRYPTED_ONLY}\" = \"1\" ] && PARAMS=\"-k _\"\n/usr/bin/hbbs -r $REL"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/type",
    "chars": 8,
    "preview": "longrun\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/type",
    "chars": 8,
    "preview": "oneshot\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up",
    "chars": 43,
    "preview": "/etc/s6-overlay/s6-rc.d/key-secret/up.real\n"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up.real",
    "chars": 1704,
    "preview": "#!/command/with-contenv sh\n\nif [ ! -d /data ] ; then\n  mkdir /data\nfi\n\n# normal docker secrets\nif [ ! -f /data/id_ed2551"
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbr",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbs",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/key-secret",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "docker/rootfs/usr/bin/healthcheck.sh",
    "chars": 159,
    "preview": "#!/bin/sh\n\n/package/admin/s6/command/s6-svstat /run/s6-rc/servicedirs/hbbr || exit 1\n/package/admin/s6/command/s6-svstat"
  },
  {
    "path": "docker-classic/Dockerfile",
    "chars": 90,
    "preview": "FROM scratch\nCOPY hbbs /usr/bin/hbbs\nCOPY hbbr /usr/bin/hbbr\nWORKDIR /root\nENV HOME=/root\n"
  },
  {
    "path": "docker-compose.yml",
    "chars": 659,
    "preview": "version: '3'\n\nnetworks:\n  rustdesk-net:\n    external: false\n\nservices:\n  hbbs:\n    container_name: hbbs\n    ports:\n     "
  },
  {
    "path": "kubernetes/example.yaml",
    "chars": 1949,
    "preview": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: rustdesk-server\nspec:\n  replicas: 1\n  strategy:\n    type: Recreat"
  },
  {
    "path": "rcd/rustdesk-hbbr",
    "chars": 2293,
    "preview": "#!/bin/sh\n\n# PROVIDE: rustdesk_hbbr\n# REQUIRE: LOGIN\n# KEYWORD: shutdown\n#\n# Add the following lines to /etc/rc.conf.loc"
  },
  {
    "path": "rcd/rustdesk-hbbs",
    "chars": 2559,
    "preview": "#!/bin/sh\n\n# PROVIDE: rustdesk_hbbs\n# REQUIRE: LOGIN\n# KEYWORD: shutdown\n#\n# Add the following lines to /etc/rc.conf.loc"
  },
  {
    "path": "src/common.rs",
    "chars": 6795,
    "preview": "use clap::App;\nuse hbb_common::{\n    allow_err, anyhow::{Context, Result}, get_version_number, log, tokio, ResultType\n};"
  },
  {
    "path": "src/database.rs",
    "chars": 5004,
    "preview": "use async_trait::async_trait;\nuse hbb_common::{log, ResultType};\nuse sqlx::{\n    sqlite::SqliteConnectOptions, ConnectOp"
  },
  {
    "path": "src/hbbr.rs",
    "chars": 1344,
    "preview": "use clap::App;\nmod common;\nmod relay_server;\nuse flexi_logger::*;\nuse hbb_common::{config::RELAY_PORT, ResultType};\nuse "
  },
  {
    "path": "src/lib.rs",
    "chars": 106,
    "preview": "mod rendezvous_server;\npub use rendezvous_server::*;\npub mod common;\nmod database;\nmod peer;\nmod version;\n"
  },
  {
    "path": "src/main.rs",
    "chars": 1793,
    "preview": "// https://tools.ietf.org/rfc/rfc5128.txt\n// https://blog.csdn.net/bytxl/article/details/44344855\n\nuse flexi_logger::*;\n"
  },
  {
    "path": "src/mod.rs",
    "chars": 84,
    "preview": "pub mod relay_server;\npub mod rendezvous_server;\nmod sled_async;\nuse sled_async::*;\n"
  },
  {
    "path": "src/peer.rs",
    "chars": 5719,
    "preview": "use crate::common::*;\nuse crate::database;\nuse hbb_common::{\n    bytes::Bytes,\n    log,\n    rendezvous_proto::*,\n    tok"
  },
  {
    "path": "src/relay_server.rs",
    "chars": 22168,
    "preview": "use async_speed_limit::Limiter;\nuse async_trait::async_trait;\nuse hbb_common::{\n    allow_err, bail,\n    bytes::{Bytes, "
  },
  {
    "path": "src/rendezvous_server.rs",
    "chars": 53292,
    "preview": "use crate::common::*;\nuse crate::peer::*;\nuse hbb_common::{\n    allow_err, bail,\n    bytes::{Bytes, BytesMut},\n    bytes"
  },
  {
    "path": "src/utils.rs",
    "chars": 5299,
    "preview": "use dns_lookup::{lookup_addr, lookup_host};\nuse hbb_common::{bail, ResultType};\nuse sodiumoxide::crypto::sign;\nuse std::"
  },
  {
    "path": "systemd/rustdesk-hbbr.service",
    "chars": 405,
    "preview": "\n[Unit]\nDescription=Rustdesk Relay Server\n\n[Service]\nType=simple\nLimitNOFILE=1000000\nExecStart=/usr/bin/hbbr\nWorkingDire"
  },
  {
    "path": "systemd/rustdesk-hbbs.service",
    "chars": 406,
    "preview": "\n[Unit]\nDescription=Rustdesk Signal Server\n\n[Service]\nType=simple\nLimitNOFILE=1000000\nExecStart=/usr/bin/hbbs\nWorkingDir"
  },
  {
    "path": "ui/.cargo/config.toml",
    "chars": 278,
    "preview": "[target.x86_64-pc-windows-msvc]\nrustflags = [\"-Ctarget-feature=+crt-static\"]\n[target.i686-pc-windows-msvc]\nrustflags = ["
  },
  {
    "path": "ui/.gitignore",
    "chars": 74,
    "preview": "# Generated by Cargo\n# will have compiled files and executables\n/target/\n\n"
  },
  {
    "path": "ui/Cargo.toml",
    "chars": 1061,
    "preview": "[package]\nname = \"rustdesk_server\"\nversion = \"0.1.2\"\ndescription = \"rustdesk server gui\"\nauthors = [\"elilchen\"]\nedition "
  },
  {
    "path": "ui/build.rs",
    "chars": 597,
    "preview": "fn main() {\n    tauri_build::build();\n    if cfg!(target_os = \"windows\") {\n        let mut res = winres::WindowsResource"
  },
  {
    "path": "ui/html/.gitignore",
    "chars": 253,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
  },
  {
    "path": "ui/html/index.html",
    "chars": 543,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, init"
  },
  {
    "path": "ui/html/main.js",
    "chars": 5296,
    "preview": "import 'codemirror/lib/codemirror.css';\nimport './style.css';\nimport 'codemirror/mode/toml/toml.js';\nimport CodeMirror f"
  },
  {
    "path": "ui/html/package.json",
    "chars": 286,
    "preview": "{\n  \"name\": \"rustdesk_server\",\n  \"private\": true,\n  \"version\": \"0.1.2\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"v"
  },
  {
    "path": "ui/html/style.css",
    "chars": 513,
    "preview": "body {\n    visibility: visible !important;\n    margin: 0;\n    background: #fff;\n}\n\n.CodeMirror {\n    height: calc(100vh "
  },
  {
    "path": "ui/html/vite.config.js",
    "chars": 138,
    "preview": "import { defineConfig } from 'vite';\n\nexport default defineConfig({\n    server: {\n        port: '5177',\n        strictPo"
  },
  {
    "path": "ui/setup/service/run.cmd",
    "chars": 492,
    "preview": "@echo off\n%~d0\ncd \"%~dp0\"\nset nssm=\"%cd%\\nssm\"\ncd ..\n\n%nssm% install %1 \"%cd%\\bin\\%1.exe\"\n\n%nssm% set %1 DisplayName %1\n"
  },
  {
    "path": "ui/setup.nsi",
    "chars": 6530,
    "preview": "Unicode true\n\n####################################################################\n# Includes\n\n!include nsDialogs.nsh\n!"
  },
  {
    "path": "ui/src/adapter/mod.rs",
    "chars": 69,
    "preview": "pub mod view;\npub mod service;\n\npub use view::*;\npub use service::*;\n"
  },
  {
    "path": "ui/src/adapter/service/mod.rs",
    "chars": 38,
    "preview": "pub mod windows;\n\npub use windows::*;\n"
  },
  {
    "path": "ui/src/adapter/service/windows.rs",
    "chars": 3468,
    "preview": "use std::{ffi::OsStr, process::Command};\n\nuse crate::{path, usecase::service::*};\nuse derive_new::new;\nuse windows_servi"
  },
  {
    "path": "ui/src/adapter/view/desktop.rs",
    "chars": 9165,
    "preview": "use std::{\n    process::exit,\n    time::{Duration, Instant},\n};\n\nuse crate::{\n    path,\n    usecase::{view::Event, Deskt"
  },
  {
    "path": "ui/src/adapter/view/mod.rs",
    "chars": 38,
    "preview": "pub mod desktop;\n\npub use desktop::*;\n"
  },
  {
    "path": "ui/src/lib.rs",
    "chars": 318,
    "preview": "use std::{env::current_exe, path::PathBuf};\n\nuse once_cell::sync::OnceCell;\n\npub mod adapter;\npub mod usecase;\n\npub stat"
  },
  {
    "path": "ui/src/main.rs",
    "chars": 726,
    "preview": "#![cfg_attr(\n    all(not(debug_assertions), target_os = \"windows\"),\n    windows_subsystem = \"windows\"\n)]\n\nuse async_std:"
  },
  {
    "path": "ui/src/usecase/mod.rs",
    "chars": 147,
    "preview": "pub mod presenter;\npub mod service;\npub mod view;\npub mod watcher;\n\npub use presenter::*;\npub use service::*;\npub use vi"
  },
  {
    "path": "ui/src/usecase/presenter.rs",
    "chars": 2551,
    "preview": "use std::time::{Duration, Instant};\n\nuse super::{service, DesktopServiceState, Event};\nuse crate::BUFFER;\nuse async_std:"
  },
  {
    "path": "ui/src/usecase/service.rs",
    "chars": 506,
    "preview": "use crate::adapter;\n\npub fn create() -> Option<Box<dyn IDesktopService + Send>> {\n    if cfg!(target_os = \"windows\") {\n "
  },
  {
    "path": "ui/src/usecase/view.rs",
    "chars": 566,
    "preview": "use super::DesktopServiceState;\nuse crate::adapter::desktop;\nuse crossbeam_channel::{Receiver, Sender};\n\npub async fn cr"
  },
  {
    "path": "ui/src/usecase/watcher.rs",
    "chars": 1325,
    "preview": "use std::{path::Path, time::Duration};\n\nuse super::Event;\nuse crate::path;\nuse async_std::task::{sleep, spawn_blocking};"
  },
  {
    "path": "ui/tauri.conf.json",
    "chars": 1869,
    "preview": "{\n  \"build\": {\n    \"beforeBuildCommand\": \"npm run build\",\n    \"beforeDevCommand\": \"npm run dev\",\n    \"devPath\": \"http://"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the rustdesk/rustdesk-server GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 87 files (250.5 KB), approximately 62.4k tokens, and a symbol index with 166 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!