mirror of
https://github.com/rustdesk/rustdesk-server.git
synced 2026-02-19 23:48:26 +08:00
Compare commits
149 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10bb0530ae | ||
|
|
7c3be2d9fb | ||
|
|
14301a7d5f | ||
|
|
d0841f7558 | ||
|
|
467298efa7 | ||
|
|
75203d2e4e | ||
|
|
27d8f9cbb4 | ||
|
|
7a0e300ff9 | ||
|
|
b2f381913d | ||
|
|
6ec46cb95f | ||
|
|
e2f4962ba8 | ||
|
|
7e307a5a1c | ||
|
|
33f54ba5aa | ||
|
|
6a83ffea62 | ||
|
|
af848f96df | ||
|
|
d88e4b5151 | ||
|
|
fe3b42809a | ||
|
|
2830be95a7 | ||
|
|
a974906fdc | ||
|
|
17ddc89bd0 | ||
|
|
088a009078 | ||
|
|
be2ce5c93b | ||
|
|
f8936eff93 | ||
|
|
accd96f1d8 | ||
|
|
32ee474813 | ||
|
|
46a7c025a0 | ||
|
|
3ca4035d0c | ||
|
|
86a75451d8 | ||
|
|
8cdfe0fec6 | ||
|
|
5aaad36729 | ||
|
|
fc83fa0a04 | ||
|
|
338af1af9d | ||
|
|
6538023a11 | ||
|
|
f139ad69a1 | ||
|
|
55fcf241c6 | ||
|
|
ebd73e1a09 | ||
|
|
00e6a016f8 | ||
|
|
78d7e9437e | ||
|
|
6bd5621fb0 | ||
|
|
ee794d2e40 | ||
|
|
605d0dd6c1 | ||
|
|
ebbe5d5297 | ||
|
|
cd1a9885db | ||
|
|
81d4fb6d6a | ||
|
|
a766aaf165 | ||
|
|
55b841afb5 | ||
|
|
d48913d7b5 | ||
|
|
1557203912 | ||
|
|
0e01cfcd3a | ||
|
|
e70d82b30f | ||
|
|
60a6d672c5 | ||
|
|
d7b2060a5b | ||
|
|
75a40412b4 | ||
|
|
93a89b8ea3 | ||
|
|
8f5ce48939 | ||
|
|
2314783d42 | ||
|
|
753c774380 | ||
|
|
f626f82a94 | ||
|
|
e732599941 | ||
|
|
29b45dddb4 | ||
|
|
650f2410ed | ||
|
|
011b316183 | ||
|
|
24620c0a07 | ||
|
|
fa2b42db76 | ||
|
|
099aaa6b55 | ||
|
|
85af668a4f | ||
|
|
c16101a44c | ||
|
|
4baab96183 | ||
|
|
74cb82c8a2 | ||
|
|
1b440b61e7 | ||
|
|
6aa0019f8d | ||
|
|
506b0b5364 | ||
|
|
bf3e9471a6 | ||
|
|
4bdc205fca | ||
|
|
cbadfcdfb1 | ||
|
|
d878222fc1 | ||
|
|
ca2bc99a38 | ||
|
|
848b5aedb7 | ||
|
|
9036b7b9fa | ||
|
|
1c5d4c3cb2 | ||
|
|
b1ad5c2e0c | ||
|
|
6991b6eca0 | ||
|
|
f6c5088aad | ||
|
|
baecd45f27 | ||
|
|
f7fc45a3d2 | ||
|
|
a4940f4634 | ||
|
|
545ae2fd93 | ||
|
|
8c477c8cd0 | ||
|
|
ccc870de77 | ||
|
|
70e6cf13ec | ||
|
|
dbab22cbbc | ||
|
|
fab70ce8e7 | ||
|
|
d11607fb6c | ||
|
|
51d8cd80c1 | ||
|
|
269f2fe0eb | ||
|
|
2d385d88d3 | ||
|
|
595aeb6d50 | ||
|
|
06bd1117f6 | ||
|
|
ee04df9779 | ||
|
|
a98d322685 | ||
|
|
670fb87ee1 | ||
|
|
50d7975ad8 | ||
|
|
003d9f1324 | ||
|
|
26549d7e7e | ||
|
|
913de8515e | ||
|
|
3340322355 | ||
|
|
06409279f4 | ||
|
|
0862bc8c04 | ||
|
|
acaee5b7a4 | ||
|
|
bfcfa68eae | ||
|
|
39153ce147 | ||
|
|
57cbac7079 | ||
|
|
8fafadd1cb | ||
|
|
98778beed3 | ||
|
|
2d5429640c | ||
|
|
eaf57b4a40 | ||
|
|
81d65623a3 | ||
|
|
052788823f | ||
|
|
7938c3d22e | ||
|
|
dd7dec8435 | ||
|
|
e071dbcef0 | ||
|
|
de3ee5be04 | ||
|
|
6c6dba5a8a | ||
|
|
104fb00d88 | ||
|
|
e4b2fc15b6 | ||
|
|
38dee4794a | ||
|
|
2c25ee12e5 | ||
|
|
1962647b1a | ||
|
|
c87e7bc848 | ||
|
|
8dfb8f43ef | ||
|
|
d624e59021 | ||
|
|
26c845e248 | ||
|
|
cf4b721d48 | ||
|
|
59d82b4869 | ||
|
|
f6792ddbca | ||
|
|
063b454368 | ||
|
|
b5c71109b0 | ||
|
|
b487badbc3 | ||
|
|
82ad556792 | ||
|
|
9bdd283548 | ||
|
|
cb26ce5bbc | ||
|
|
0977cf427e | ||
|
|
b0b1981ac9 | ||
|
|
a39c7edbf9 | ||
|
|
df2e4bb411 | ||
|
|
af2b0e050b | ||
|
|
1507a733ed | ||
|
|
03ca2a9517 | ||
|
|
b3f39598a7 |
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
||||
* text=auto
|
||||
14
.github/ISSUE_TEMPLATE/ask-a-question.md
vendored
Normal file
14
.github/ISSUE_TEMPLATE/ask-a-question.md
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: Ask a question
|
||||
about: Ask the community for help
|
||||
title: ''
|
||||
labels: 'question'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
This is the place for generic questions. Please stay on topic and be polite.
|
||||
|
||||
**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
|
||||
35
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
35
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
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
|
||||
|
||||
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
25
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
25
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
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
|
||||
|
||||
419
.github/workflows/build.yaml
vendored
Normal file
419
.github/workflows/build.yaml
vendored
Normal file
@@ -0,0 +1,419 @@
|
||||
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_USERNAME is the username you normally use to login at https://hub.docker.com/
|
||||
# DOCKER_PASSWORD is a token you should create under "account settings / security" with read/write access
|
||||
|
||||
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
|
||||
|
||||
jobs:
|
||||
|
||||
# binary build
|
||||
build:
|
||||
|
||||
name: Build - ${{ matrix.job.name }}
|
||||
runs-on: ubuntu-18.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" }
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: "1.62"
|
||||
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@v3
|
||||
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-2019
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: "1.62"
|
||||
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: Sign exe files
|
||||
uses: GermanBluefox/code-sign-action@v7
|
||||
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 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
|
||||
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@v3
|
||||
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-18.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- { os: "linux", name: "amd64" }
|
||||
- { os: "linux", name: "arm64v8" }
|
||||
- { os: "linux", name: "armv7" }
|
||||
- { os: "linux", name: "i386" }
|
||||
- { os: "windows", name: "x86_64" }
|
||||
|
||||
steps:
|
||||
|
||||
- name: Download binaries (${{ matrix.job.os }} - ${{ matrix.job.name }})
|
||||
uses: actions/download-artifact@v3
|
||||
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 }}.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 }}.zip
|
||||
|
||||
# docker build and push of single-arch images
|
||||
docker:
|
||||
|
||||
name: Docker push - ${{ matrix.job.name }}
|
||||
needs: build
|
||||
runs-on: ubuntu-18.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
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@v3
|
||||
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_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- 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@v3
|
||||
with:
|
||||
context: "./docker"
|
||||
platforms: ${{ matrix.job.docker_platform }}
|
||||
push: true
|
||||
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 }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
# docker build and push of multiarch images
|
||||
docker-manifest:
|
||||
|
||||
name: Docker manifest
|
||||
needs: docker
|
||||
runs-on: ubuntu-18.04
|
||||
|
||||
steps:
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_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
|
||||
|
||||
# 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@master
|
||||
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@master
|
||||
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@master
|
||||
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
|
||||
|
||||
|
||||
|
||||
# docker build and push of classic images
|
||||
docker-classic:
|
||||
|
||||
name: Docker push classic - ${{ matrix.job.name }}
|
||||
needs: build
|
||||
runs-on: ubuntu-18.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- { name: "amd64", docker_platform: "linux/amd64", tag: "latest" }
|
||||
- { name: "arm64v8", docker_platform: "linux/arm64", tag: "latest-arm64v8" }
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Download binaries
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: binaries-linux-${{ matrix.job.name }}
|
||||
path: docker-classic/
|
||||
|
||||
- name: Make binaries executable
|
||||
run: chmod -v a+x docker-classic/hbb*
|
||||
|
||||
- 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_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- 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: Build and push Docker image
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: "./docker-classic"
|
||||
platforms: ${{ matrix.job.docker_platform }}
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.DOCKER_IMAGE_CLASSIC }}:${{ matrix.job.tag }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
|
||||
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
|
||||
|
||||
- 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@v3
|
||||
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
|
||||
72
.github/workflows/test.yml
vendored
Normal file
72
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: check
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all
|
||||
|
||||
fmt:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
components: rustfmt
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
|
||||
clippy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: --all -- -D warnings
|
||||
17
.gitignore
vendored
17
.gitignore
vendored
@@ -1,6 +1,11 @@
|
||||
/target
|
||||
**/*.rs.bk
|
||||
version.rs
|
||||
sled.db
|
||||
hbbs.sh
|
||||
hbbs.conf
|
||||
target
|
||||
id*
|
||||
db*
|
||||
debian-build
|
||||
debian/.debhelper
|
||||
debian/debhelper-build-stamp
|
||||
.DS_Store
|
||||
.vscode
|
||||
src/version.rs
|
||||
db_v2.sqlite3
|
||||
test.*
|
||||
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -1,3 +0,0 @@
|
||||
[submodule "libs/hbb_common"]
|
||||
path = libs/hbb_common
|
||||
url = https://github.com/open-trade/hbb_common
|
||||
6
.vscode/settings.json
vendored
Normal file
6
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"rust.checkWith": "clippy",
|
||||
"rust.formatOnSave": true,
|
||||
"rust.checkOnSave": true,
|
||||
"rust.useNewErrorFormat": true
|
||||
}
|
||||
2488
Cargo.lock
generated
2488
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
50
Cargo.toml
50
Cargo.toml
@@ -1,14 +1,19 @@
|
||||
[package]
|
||||
name = "hbbs"
|
||||
version = "1.1.4"
|
||||
authors = ["open-trade <info@opentradesolutions.com>"]
|
||||
edition = "2018"
|
||||
build= "build.rs"
|
||||
version = "1.1.7"
|
||||
authors = ["open-trade <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]
|
||||
@@ -17,22 +22,39 @@ serde_derive = "1.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
lazy_static = "1.4"
|
||||
clap = "2.33"
|
||||
rust-ini = "0.16"
|
||||
minreq = { version = "2.3.1", features = ["punycode"] }
|
||||
clap = "2"
|
||||
rust-ini = "0.18"
|
||||
minreq = { version = "2.4", features = ["punycode"] }
|
||||
machine-uid = "0.2"
|
||||
mac_address = "1.1"
|
||||
whoami = "0.9"
|
||||
whoami = "1.2"
|
||||
base64 = "0.13"
|
||||
cryptoxide = "0.3"
|
||||
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"] }
|
||||
ipnetwork = "0.20"
|
||||
local-ip-address = "0.4"
|
||||
dns-lookup = "1.0.8"
|
||||
ping = "0.4.0"
|
||||
|
||||
[build-dependencies]
|
||||
hbb_common = { path = "libs/hbb_common" }
|
||||
|
||||
[workspace]
|
||||
members = ["libs/hbb_common"]
|
||||
|
||||
[dependencies.rocksdb]
|
||||
default-features = false
|
||||
features = ["lz4"]
|
||||
version = "0.15"
|
||||
exclude = ["ui"]
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
FROM ubuntu:20.04
|
||||
COPY target/release/hbbs /usr/bin/hbbs
|
||||
COPY target/release/hbbr /usr/bin/hbbr
|
||||
WORKDIR /root
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
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/>.
|
||||
335
README.md
Normal file
335
README.md
Normal file
@@ -0,0 +1,335 @@
|
||||
# RustDesk Server Program
|
||||
|
||||
[](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)
|
||||
|
||||
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 wanna 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.
|
||||
|
||||
## Docker images
|
||||
|
||||
Docker images are automatically generated and published on every github release. We have 2 kind of images.
|
||||
|
||||
### Classic image
|
||||
|
||||
These images are build against `ubuntu-20.04` with the only addition of the main binaries (`hbbr` and `hbbs`). They're available on [Docker hub](https://hub.docker.com/r/rustdesk/rustdesk-server/) with these tags:
|
||||
|
||||
| architecture | image:tag |
|
||||
| --- | --- |
|
||||
| amd64 | `rustdesk/rustdesk-server:latest` |
|
||||
| arm64v8 | `rustdesk/rustdesk-server:latest-arm64v8` |
|
||||
|
||||
You can start these images directly with `docker run` with these commands:
|
||||
|
||||
```bash
|
||||
docker run --name hbbs --net=host -v "$PWD/data:/root" -d rustdesk/rustdesk-server:latest hbbs -r <relay-server-ip[:port]>
|
||||
docker run --name hbbr --net=host -v "$PWD/data:/root" -d rustdesk/rustdesk-server:latest hbbr
|
||||
```
|
||||
|
||||
or without --net=host, but P2P direct connection can not work.
|
||||
|
||||
For systems using SELinux, replacing `/root` by `/root:z` is required for the containers to run correctly. Alternatively, SELinux container separation can be disabled completely adding the option `--security-opt label=disable`.
|
||||
|
||||
```bash
|
||||
docker run --name hbbs -p 21115:21115 -p 21116:21116 -p 21116:21116/udp -p 21118:21118 -v "$PWD/data:/root" -d rustdesk/rustdesk-server:latest hbbs -r <relay-server-ip[:port]>
|
||||
docker run --name hbbr -p 21117:21117 -p 21119:21119 -v "$PWD/data:/root" -d rustdesk/rustdesk-server:latest hbbr
|
||||
```
|
||||
|
||||
The `relay-server-ip` parameter is the IP address (or dns name) of the server running these containers. The **optional** `port` parameter has to be used if you use a port different than **21117** for `hbbr`.
|
||||
|
||||
You can also use docker-compose, using this configuration as a template:
|
||||
|
||||
```yaml
|
||||
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
|
||||
```
|
||||
|
||||
Edit line 16 to point to your relay server (the one listening on port 21117). You can also edit the volume lines (L18 and L33) if you need.
|
||||
|
||||
(docker-compose credit goes to @lukebarone and @QuiGonLeong)
|
||||
|
||||
## S6-overlay based images
|
||||
|
||||
These images are build against `busybox:stable` with the addition of the binaries (both hbbr and hbbs) and [S6-overlay](https://github.com/just-containers/s6-overlay). They're available on [Docker hub](https://hub.docker.com/r/rustdesk/rustdesk-server-s6/) with these tags:
|
||||
|
||||
| architecture | version | image:tag |
|
||||
| --- | --- | --- |
|
||||
| multiarch | latest | `rustdesk/rustdesk-server-s6:latest` |
|
||||
| amd64 | latest | `rustdesk/rustdesk-server-s6:latest-amd64` |
|
||||
| i386 | latest | `rustdesk/rustdesk-server-s6:latest-i386` |
|
||||
| arm64v8 | latest | `rustdesk/rustdesk-server-s6:latest-arm64v8` |
|
||||
| armv7 | latest | `rustdesk/rustdesk-server-s6:latest-armv7` |
|
||||
| multiarch | 2 | `rustdesk/rustdesk-server-s6:2` |
|
||||
| amd64 | 2 | `rustdesk/rustdesk-server-s6:2-amd64` |
|
||||
| i386 | 2 | `rustdesk/rustdesk-server-s6:2-i386` |
|
||||
| arm64v8 | 2 | `rustdesk/rustdesk-server-s6:2-arm64v8` |
|
||||
| armv7 | 2 | `rustdesk/rustdesk-server-s6:2-armv7` |
|
||||
| multiarch | 2.0.0 | `rustdesk/rustdesk-server-s6:2.0.0` |
|
||||
| amd64 | 2.0.0 | `rustdesk/rustdesk-server-s6:2.0.0-amd64` |
|
||||
| i386 | 2.0.0 | `rustdesk/rustdesk-server-s6:2.0.0-i386` |
|
||||
| arm64v8 | 2.0.0 | `rustdesk/rustdesk-server-s6:2.0.0-arm64v8` |
|
||||
| armv7 | 2.0.0 | `rustdesk/rustdesk-server-s6:2.0.0-armv7` |
|
||||
|
||||
You're strongly encuraged to use the `multiarch` image either with the `major version` or `latest` tag.
|
||||
|
||||
The S6-overlay acts as a supervisor and keeps both process running, so with this image there's no need to have two separate running containers.
|
||||
|
||||
You can start these images directly with `docker run` with this command:
|
||||
|
||||
```bash
|
||||
docker run --name rustdesk-server \
|
||||
--net=host \
|
||||
-e "RELAY=rustdeskrelay.example.com" \
|
||||
-e "ENCRYPTED_ONLY=1" \
|
||||
-v "$PWD/data:/data" -d rustdesk/rustdesk-server-s6:latest
|
||||
```
|
||||
|
||||
or without --net=host, but P2P direct connection can not work.
|
||||
|
||||
```bash
|
||||
docker run --name rustdesk-server \
|
||||
-p 21115:21115 -p 21116:21116 -p 21116:21116/udp \
|
||||
-p 21117:21117 -p 21118:21118 -p 21119:21119 \
|
||||
-e "RELAY=rustdeskrelay.example.com" \
|
||||
-e "ENCRYPTED_ONLY=1" \
|
||||
-v "$PWD/data:/data" -d rustdesk/rustdesk-server-s6:latest
|
||||
```
|
||||
|
||||
Or you can use a docker-compose file:
|
||||
|
||||
```yaml
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
rustdesk-server:
|
||||
container_name: rustdesk-server
|
||||
ports:
|
||||
- 21115:21115
|
||||
- 21116:21116
|
||||
- 21116:21116/udp
|
||||
- 21117:21117
|
||||
- 21118:21118
|
||||
- 21119:21119
|
||||
image: rustdesk/rustdesk-server-s6:latest
|
||||
environment:
|
||||
- "RELAY=rustdesk.example.com:21117"
|
||||
- "ENCRYPTED_ONLY=1"
|
||||
volumes:
|
||||
- ./data:/data
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
For this container image, you can use these environment variables, **in addition** to the ones specified in the following **ENV variables** section:
|
||||
|
||||
| variable | optional | description |
|
||||
| --- | --- | --- |
|
||||
| RELAY | no | the IP address/DNS name of the machine running this container |
|
||||
| ENCRYPTED_ONLY | yes | if set to **"1"** unencrypted connection will not be accepted |
|
||||
| KEY_PUB | yes | public part of the key pair |
|
||||
| KEY_PRIV | yes | private part of the key pair |
|
||||
|
||||
### Secret management in S6-overlay based images
|
||||
|
||||
You can obviously keep the key pair in a docker volume, but the best practices tells you to not write the keys on the filesystem; so we provide a couple of options.
|
||||
|
||||
On container startup, the presence of the keypair is checked (`/data/id_ed25519.pub` and `/data/id_ed25519`) and if one of these keys doesn't exist, it's recreated from ENV variables or docker secrets.
|
||||
Then the validity of the keypair is checked: if public and private keys doesn't match, the container will stop.
|
||||
If you provide no keys, `hbbs` will generate one for you, and it'll place it in the default location.
|
||||
|
||||
#### Use ENV to store the key pair
|
||||
|
||||
You can use docker environment variables to store the keys. Just follow this examples:
|
||||
|
||||
```bash
|
||||
docker run --name rustdesk-server \
|
||||
--net=host \
|
||||
-e "RELAY=rustdeskrelay.example.com" \
|
||||
-e "ENCRYPTED_ONLY=1" \
|
||||
-e "DB_URL=/db/db_v2.sqlite3" \
|
||||
-e "KEY_PRIV=FR2j78IxfwJNR+HjLluQ2Nh7eEryEeIZCwiQDPVe+PaITKyShphHAsPLn7So0OqRs92nGvSRdFJnE2MSyrKTIQ==" \
|
||||
-e "KEY_PUB=iEyskoaYRwLDy5+0qNDqkbPdpxr0kXRSZxNjEsqykyE=" \
|
||||
-v "$PWD/db:/db" -d rustdesk/rustdesk-server-s6:latest
|
||||
```
|
||||
|
||||
```yaml
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
rustdesk-server:
|
||||
container_name: rustdesk-server
|
||||
ports:
|
||||
- 21115:21115
|
||||
- 21116:21116
|
||||
- 21116:21116/udp
|
||||
- 21117:21117
|
||||
- 21118:21118
|
||||
- 21119:21119
|
||||
image: rustdesk/rustdesk-server-s6:latest
|
||||
environment:
|
||||
- "RELAY=rustdesk.example.com:21117"
|
||||
- "ENCRYPTED_ONLY=1"
|
||||
- "DB_URL=/db/db_v2.sqlite3"
|
||||
- "KEY_PRIV=FR2j78IxfwJNR+HjLluQ2Nh7eEryEeIZCwiQDPVe+PaITKyShphHAsPLn7So0OqRs92nGvSRdFJnE2MSyrKTIQ=="
|
||||
- "KEY_PUB=iEyskoaYRwLDy5+0qNDqkbPdpxr0kXRSZxNjEsqykyE="
|
||||
volumes:
|
||||
- ./db:/db
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
#### Use Docker secrets to store the key pair
|
||||
|
||||
You can alternatively use docker secrets to store the keys.
|
||||
This is useful if you're using **docker-compose** or **docker swarm**.
|
||||
Just follow this examples:
|
||||
|
||||
```bash
|
||||
cat secrets/id_ed25519.pub | docker secret create key_pub -
|
||||
cat secrets/id_ed25519 | docker secret create key_priv -
|
||||
docker service create --name rustdesk-server \
|
||||
--secret key_priv --secret key_pub \
|
||||
--net=host \
|
||||
-e "RELAY=rustdeskrelay.example.com" \
|
||||
-e "ENCRYPTED_ONLY=1" \
|
||||
-e "DB_URL=/db/db_v2.sqlite3" \
|
||||
--mount "type=bind,source=$PWD/db,destination=/db" \
|
||||
rustdesk/rustdesk-server-s6:latest
|
||||
```
|
||||
|
||||
```yaml
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
rustdesk-server:
|
||||
container_name: rustdesk-server
|
||||
ports:
|
||||
- 21115:21115
|
||||
- 21116:21116
|
||||
- 21116:21116/udp
|
||||
- 21117:21117
|
||||
- 21118:21118
|
||||
- 21119:21119
|
||||
image: rustdesk/rustdesk-server-s6:latest
|
||||
environment:
|
||||
- "RELAY=rustdesk.example.com:21117"
|
||||
- "ENCRYPTED_ONLY=1"
|
||||
- "DB_URL=/db/db_v2.sqlite3"
|
||||
volumes:
|
||||
- ./db:/db
|
||||
restart: unless-stopped
|
||||
secrets:
|
||||
- key_pub
|
||||
- key_priv
|
||||
|
||||
secrets:
|
||||
key_pub:
|
||||
file: secrets/id_ed25519.pub
|
||||
key_priv:
|
||||
file: secrets/id_ed25519
|
||||
```
|
||||
|
||||
## How to create a keypair
|
||||
|
||||
A keypair is needed for encryption; you can provide it, as explained before, but you need a way to create one.
|
||||
|
||||
You can use this command to generate a keypair:
|
||||
|
||||
```bash
|
||||
/usr/bin/rustdesk-utils genkeypair
|
||||
```
|
||||
|
||||
If you don't have (or don't want) the `rustdesk-utils` package installed on your system, you can invoke the same command with docker:
|
||||
|
||||
```bash
|
||||
docker run --rm --entrypoint /usr/bin/rustdesk-utils rustdesk/rustdesk-server-s6:latest genkeypair
|
||||
```
|
||||
|
||||
The output will be something like this:
|
||||
|
||||
```text
|
||||
Public Key: 8BLLhtzUBU/XKAH4mep3p+IX4DSApe7qbAwNH9nv4yA=
|
||||
Secret Key: egAVd44u33ZEUIDTtksGcHeVeAwywarEdHmf99KM5ajwEsuG3NQFT9coAfiZ6nen4hfgNICl7upsDA0f2e/jIA==
|
||||
```
|
||||
|
||||
## .deb packages
|
||||
|
||||
Separate .deb packages are available for each binary, you can find them in the [releases](https://github.com/rustdesk/rustdesk-server/releases).
|
||||
These packages are meant for the following distributions:
|
||||
|
||||
- Ubuntu 22.04 LTS
|
||||
- Ubuntu 20.04 LTS
|
||||
- Ubuntu 18.04 LTS
|
||||
- Debian 11 bullseye
|
||||
- Debian 10 buster
|
||||
|
||||
## ENV variables
|
||||
|
||||
hbbs and hbbr can be configured using these ENV variables.
|
||||
You can specify the variables as usual or use an `.env` file.
|
||||
|
||||
| variable | binary | description |
|
||||
| --- | --- | --- |
|
||||
| ALWAYS_USE_RELAY | hbbs | if set to **"Y"** disallows direct peer connection |
|
||||
| DB_URL | hbbs | path for database file |
|
||||
| DOWNGRADE_START_CHECK | hbbr | delay (in seconds) before downgrade check |
|
||||
| DOWNGRADE_THRESHOLD | hbbr | threshold of downgrade check (bit/ms) |
|
||||
| KEY | hbbs/hbbr | if set force the use of a specific key, if set to **"_"** force the use of any key |
|
||||
| LIMIT_SPEED | hbbr | speed limit (in Mb/s) |
|
||||
| PORT | hbbs/hbbr | listening port (21116 for hbbs - 21117 for hbbr) |
|
||||
| RELAY_SERVERS | hbbs | IP address/DNS name of the machines running hbbr (separated by comma) |
|
||||
| RUST_LOG | all | set debug level (error\|warn\|info\|debug\|trace) |
|
||||
| SINGLE_BANDWIDTH | hbbr | max bandwidth for a single connection (in Mb/s) |
|
||||
| TOTAL_BANDWIDTH | hbbr | max total bandwidth (in Mb/s) |
|
||||
BIN
db_v2.sqlite3
Normal file
BIN
db_v2.sqlite3
Normal file
Binary file not shown.
11
debian/changelog
vendored
Normal file
11
debian/changelog
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
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
|
||||
1
debian/compat
vendored
Normal file
1
debian/compat
vendored
Normal file
@@ -0,0 +1 @@
|
||||
10
|
||||
27
debian/control.tpl
vendored
Normal file
27
debian/control.tpl
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
679
debian/copyright
vendored
Normal file
679
debian/copyright
vendored
Normal file
@@ -0,0 +1,679 @@
|
||||
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/>.
|
||||
6
debian/rules
vendored
Executable file
6
debian/rules
vendored
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/make -f
|
||||
%:
|
||||
dh $@
|
||||
|
||||
override_dh_builddeb:
|
||||
dh_builddeb -- -Zgzip
|
||||
2
debian/rustdesk-server-hbbr.install
vendored
Normal file
2
debian/rustdesk-server-hbbr.install
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
bin/hbbr usr/bin
|
||||
systemd/rustdesk-hbbr.service lib/systemd/system
|
||||
28
debian/rustdesk-server-hbbr.postinst
vendored
Normal file
28
debian/rustdesk-server-hbbr.postinst
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
SERVICE=rustdesk-hbbr.service
|
||||
|
||||
if [ "$1" = "configure" ]; then
|
||||
mkdir -p /var/log/rustdesk
|
||||
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
|
||||
18
debian/rustdesk-server-hbbr.postrm
vendored
Normal file
18
debian/rustdesk-server-hbbr.postrm
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
SERVICE=rustdesk-hbbr.service
|
||||
|
||||
systemctl --system daemon-reload >/dev/null || true
|
||||
|
||||
if [ "$1" = "purge" ]; then
|
||||
rm -rf /var/lib/rustdesk-server/ /var/log/rustdesk/rustdesk-hbbr.* /var/log/rustdesk/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
|
||||
13
debian/rustdesk-server-hbbr.prerm
vendored
Normal file
13
debian/rustdesk-server-hbbr.prerm
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
#!/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
|
||||
2
debian/rustdesk-server-hbbs.install
vendored
Normal file
2
debian/rustdesk-server-hbbs.install
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
bin/hbbs usr/bin
|
||||
systemd/rustdesk-hbbs.service lib/systemd/system
|
||||
28
debian/rustdesk-server-hbbs.postinst
vendored
Normal file
28
debian/rustdesk-server-hbbs.postinst
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
SERVICE=rustdesk-hbbs.service
|
||||
|
||||
if [ "$1" = "configure" ]; then
|
||||
mkdir -p /var/log/rustdesk
|
||||
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
|
||||
18
debian/rustdesk-server-hbbs.postrm
vendored
Normal file
18
debian/rustdesk-server-hbbs.postrm
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
#!/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/
|
||||
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
|
||||
13
debian/rustdesk-server-hbbs.prerm
vendored
Normal file
13
debian/rustdesk-server-hbbs.prerm
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
#!/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
|
||||
1
debian/rustdesk-server-utils.install
vendored
Normal file
1
debian/rustdesk-server-utils.install
vendored
Normal file
@@ -0,0 +1 @@
|
||||
bin/rustdesk-utils usr/bin
|
||||
1
debian/source/format
vendored
Normal file
1
debian/source/format
vendored
Normal file
@@ -0,0 +1 @@
|
||||
3.0 (native)
|
||||
4
docker-classic/Dockerfile
Executable file
4
docker-classic/Dockerfile
Executable file
@@ -0,0 +1,4 @@
|
||||
FROM ubuntu:20.04
|
||||
COPY hbbs /usr/bin/hbbs
|
||||
COPY hbbr /usr/bin/hbbr
|
||||
WORKDIR /root
|
||||
36
docker-compose.yml
Normal file
36
docker-compose.yml
Normal file
@@ -0,0 +1,36 @@
|
||||
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
|
||||
26
docker/Dockerfile
Executable file
26
docker/Dockerfile
Executable file
@@ -0,0 +1,26 @@
|
||||
FROM busybox:stable
|
||||
|
||||
ARG S6_OVERLAY_VERSION=3.1.1.2
|
||||
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"]
|
||||
4
docker/healthcheck.sh
Executable file
4
docker/healthcheck.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/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
|
||||
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/dependencies
Normal file
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/dependencies
Normal file
@@ -0,0 +1 @@
|
||||
key-secret
|
||||
5
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/run
Executable file
5
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/run
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/command/with-contenv sh
|
||||
cd /data
|
||||
PARAMS=
|
||||
[ "${ENCRYPTED_ONLY}" = "1" ] && PARAMS="-k _"
|
||||
/usr/bin/hbbr $PARAMS
|
||||
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/type
Executable file
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbr/type
Executable file
@@ -0,0 +1 @@
|
||||
longrun
|
||||
2
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/dependencies
Normal file
2
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/dependencies
Normal file
@@ -0,0 +1,2 @@
|
||||
key-secret
|
||||
hbbr
|
||||
6
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/run
Executable file
6
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/run
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/command/with-contenv sh
|
||||
sleep 2
|
||||
cd /data
|
||||
PARAMS=
|
||||
[ "${ENCRYPTED_ONLY}" = "1" ] && PARAMS="-k _"
|
||||
/usr/bin/hbbs -r $RELAY $PARAMS
|
||||
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/type
Executable file
1
docker/rootfs/etc/s6-overlay/s6-rc.d/hbbs/type
Executable file
@@ -0,0 +1 @@
|
||||
longrun
|
||||
1
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/type
Executable file
1
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/type
Executable file
@@ -0,0 +1 @@
|
||||
oneshot
|
||||
1
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up
Executable file
1
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up
Executable file
@@ -0,0 +1 @@
|
||||
/etc/s6-overlay/s6-rc.d/key-secret/up.real
|
||||
58
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up.real
Executable file
58
docker/rootfs/etc/s6-overlay/s6-rc.d/key-secret/up.real
Executable file
@@ -0,0 +1,58 @@
|
||||
#!/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
|
||||
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbr
Executable file
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbr
Executable file
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbs
Executable file
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/hbbs
Executable file
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/key-secret
Executable file
0
docker/rootfs/etc/s6-overlay/s6-rc.d/user/contents.d/key-secret
Executable file
4
docker/rootfs/usr/bin/healthcheck.sh
Executable file
4
docker/rootfs/usr/bin/healthcheck.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/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
|
||||
Submodule libs/hbb_common deleted from ec453e5e65
4
libs/hbb_common/.gitignore
vendored
Normal file
4
libs/hbb_common/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/target
|
||||
**/*.rs.bk
|
||||
Cargo.lock
|
||||
src/protos/
|
||||
51
libs/hbb_common/Cargo.toml
Normal file
51
libs/hbb_common/Cargo.toml
Normal file
@@ -0,0 +1,51 @@
|
||||
[package]
|
||||
name = "hbb_common"
|
||||
version = "0.1.0"
|
||||
authors = ["open-trade <info@opentradesolutions.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
protobuf = { version = "3.1", features = ["with-bytes"] }
|
||||
tokio = { version = "1.20", features = ["full"] }
|
||||
tokio-util = { version = "0.7", features = ["full"] }
|
||||
futures = "0.3"
|
||||
bytes = { version = "1.2", features = ["serde"] }
|
||||
log = "0.4"
|
||||
env_logger = "0.9"
|
||||
socket2 = { version = "0.3", features = ["reuseport"] }
|
||||
zstd = "0.9"
|
||||
quinn = {version = "0.8", optional = true }
|
||||
anyhow = "1.0"
|
||||
futures-util = "0.3"
|
||||
directories-next = "2.0"
|
||||
rand = "0.8"
|
||||
serde_derive = "1.0"
|
||||
serde = "1.0"
|
||||
lazy_static = "1.4"
|
||||
confy = { git = "https://github.com/open-trade/confy" }
|
||||
dirs-next = "2.0"
|
||||
filetime = "0.2"
|
||||
sodiumoxide = "0.2"
|
||||
regex = "1.4"
|
||||
tokio-socks = { git = "https://github.com/open-trade/tokio-socks" }
|
||||
chrono = "0.4"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
mac_address = "1.1"
|
||||
machine-uid = "0.2"
|
||||
|
||||
[features]
|
||||
quic = []
|
||||
flatpak = []
|
||||
|
||||
[build-dependencies]
|
||||
protobuf-codegen = { version = "3.1" }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winapi = { version = "0.3", features = ["winuser"] }
|
||||
|
||||
[dev-dependencies]
|
||||
toml = "0.5"
|
||||
serde_json = "1.0"
|
||||
14
libs/hbb_common/build.rs
Normal file
14
libs/hbb_common/build.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
fn main() {
|
||||
let out_dir = format!("{}/protos", std::env::var("OUT_DIR").unwrap());
|
||||
|
||||
std::fs::create_dir_all(&out_dir).unwrap();
|
||||
|
||||
protobuf_codegen::Codegen::new()
|
||||
.pure()
|
||||
.out_dir(out_dir)
|
||||
.inputs(["protos/rendezvous.proto", "protos/message.proto"])
|
||||
.include("protos")
|
||||
.customize(protobuf_codegen::Customize::default().tokio_bytes(true))
|
||||
.run()
|
||||
.expect("Codegen failed.");
|
||||
}
|
||||
638
libs/hbb_common/protos/message.proto
Normal file
638
libs/hbb_common/protos/message.proto
Normal file
@@ -0,0 +1,638 @@
|
||||
syntax = "proto3";
|
||||
package hbb;
|
||||
|
||||
message EncodedVideoFrame {
|
||||
bytes data = 1;
|
||||
bool key = 2;
|
||||
int64 pts = 3;
|
||||
}
|
||||
|
||||
message EncodedVideoFrames { repeated EncodedVideoFrame frames = 1; }
|
||||
|
||||
message RGB { bool compress = 1; }
|
||||
|
||||
// planes data send directly in binary for better use arraybuffer on web
|
||||
message YUV {
|
||||
bool compress = 1;
|
||||
int32 stride = 2;
|
||||
}
|
||||
|
||||
message VideoFrame {
|
||||
oneof union {
|
||||
EncodedVideoFrames vp9s = 6;
|
||||
RGB rgb = 7;
|
||||
YUV yuv = 8;
|
||||
EncodedVideoFrames h264s = 10;
|
||||
EncodedVideoFrames h265s = 11;
|
||||
}
|
||||
int64 timestamp = 9;
|
||||
}
|
||||
|
||||
message IdPk {
|
||||
string id = 1;
|
||||
bytes pk = 2;
|
||||
}
|
||||
|
||||
message DisplayInfo {
|
||||
sint32 x = 1;
|
||||
sint32 y = 2;
|
||||
int32 width = 3;
|
||||
int32 height = 4;
|
||||
string name = 5;
|
||||
bool online = 6;
|
||||
bool cursor_embedded = 7;
|
||||
}
|
||||
|
||||
message PortForward {
|
||||
string host = 1;
|
||||
int32 port = 2;
|
||||
}
|
||||
|
||||
message FileTransfer {
|
||||
string dir = 1;
|
||||
bool show_hidden = 2;
|
||||
}
|
||||
|
||||
message LoginRequest {
|
||||
string username = 1;
|
||||
bytes password = 2;
|
||||
string my_id = 4;
|
||||
string my_name = 5;
|
||||
OptionMessage option = 6;
|
||||
oneof union {
|
||||
FileTransfer file_transfer = 7;
|
||||
PortForward port_forward = 8;
|
||||
}
|
||||
bool video_ack_required = 9;
|
||||
uint64 session_id = 10;
|
||||
string version = 11;
|
||||
}
|
||||
|
||||
message ChatMessage { string text = 1; }
|
||||
|
||||
message Features {
|
||||
bool privacy_mode = 1;
|
||||
}
|
||||
|
||||
message SupportedEncoding {
|
||||
bool h264 = 1;
|
||||
bool h265 = 2;
|
||||
}
|
||||
|
||||
message PeerInfo {
|
||||
string username = 1;
|
||||
string hostname = 2;
|
||||
string platform = 3;
|
||||
repeated DisplayInfo displays = 4;
|
||||
int32 current_display = 5;
|
||||
bool sas_enabled = 6;
|
||||
string version = 7;
|
||||
int32 conn_id = 8;
|
||||
Features features = 9;
|
||||
SupportedEncoding encoding = 10;
|
||||
}
|
||||
|
||||
message LoginResponse {
|
||||
oneof union {
|
||||
string error = 1;
|
||||
PeerInfo peer_info = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message MouseEvent {
|
||||
int32 mask = 1;
|
||||
sint32 x = 2;
|
||||
sint32 y = 3;
|
||||
repeated ControlKey modifiers = 4;
|
||||
}
|
||||
|
||||
enum KeyboardMode{
|
||||
Legacy = 0;
|
||||
Map = 1;
|
||||
Translate = 2;
|
||||
Auto = 3;
|
||||
}
|
||||
|
||||
enum ControlKey {
|
||||
Unknown = 0;
|
||||
Alt = 1;
|
||||
Backspace = 2;
|
||||
CapsLock = 3;
|
||||
Control = 4;
|
||||
Delete = 5;
|
||||
DownArrow = 6;
|
||||
End = 7;
|
||||
Escape = 8;
|
||||
F1 = 9;
|
||||
F10 = 10;
|
||||
F11 = 11;
|
||||
F12 = 12;
|
||||
F2 = 13;
|
||||
F3 = 14;
|
||||
F4 = 15;
|
||||
F5 = 16;
|
||||
F6 = 17;
|
||||
F7 = 18;
|
||||
F8 = 19;
|
||||
F9 = 20;
|
||||
Home = 21;
|
||||
LeftArrow = 22;
|
||||
/// meta key (also known as "windows"; "super"; and "command")
|
||||
Meta = 23;
|
||||
/// option key on macOS (alt key on Linux and Windows)
|
||||
Option = 24; // deprecated, use Alt instead
|
||||
PageDown = 25;
|
||||
PageUp = 26;
|
||||
Return = 27;
|
||||
RightArrow = 28;
|
||||
Shift = 29;
|
||||
Space = 30;
|
||||
Tab = 31;
|
||||
UpArrow = 32;
|
||||
Numpad0 = 33;
|
||||
Numpad1 = 34;
|
||||
Numpad2 = 35;
|
||||
Numpad3 = 36;
|
||||
Numpad4 = 37;
|
||||
Numpad5 = 38;
|
||||
Numpad6 = 39;
|
||||
Numpad7 = 40;
|
||||
Numpad8 = 41;
|
||||
Numpad9 = 42;
|
||||
Cancel = 43;
|
||||
Clear = 44;
|
||||
Menu = 45; // deprecated, use Alt instead
|
||||
Pause = 46;
|
||||
Kana = 47;
|
||||
Hangul = 48;
|
||||
Junja = 49;
|
||||
Final = 50;
|
||||
Hanja = 51;
|
||||
Kanji = 52;
|
||||
Convert = 53;
|
||||
Select = 54;
|
||||
Print = 55;
|
||||
Execute = 56;
|
||||
Snapshot = 57;
|
||||
Insert = 58;
|
||||
Help = 59;
|
||||
Sleep = 60;
|
||||
Separator = 61;
|
||||
Scroll = 62;
|
||||
NumLock = 63;
|
||||
RWin = 64;
|
||||
Apps = 65;
|
||||
Multiply = 66;
|
||||
Add = 67;
|
||||
Subtract = 68;
|
||||
Decimal = 69;
|
||||
Divide = 70;
|
||||
Equals = 71;
|
||||
NumpadEnter = 72;
|
||||
RShift = 73;
|
||||
RControl = 74;
|
||||
RAlt = 75;
|
||||
CtrlAltDel = 100;
|
||||
LockScreen = 101;
|
||||
}
|
||||
|
||||
message KeyEvent {
|
||||
bool down = 1;
|
||||
bool press = 2;
|
||||
oneof union {
|
||||
ControlKey control_key = 3;
|
||||
uint32 chr = 4;
|
||||
uint32 unicode = 5;
|
||||
string seq = 6;
|
||||
}
|
||||
repeated ControlKey modifiers = 8;
|
||||
KeyboardMode mode = 9;
|
||||
}
|
||||
|
||||
message CursorData {
|
||||
uint64 id = 1;
|
||||
sint32 hotx = 2;
|
||||
sint32 hoty = 3;
|
||||
int32 width = 4;
|
||||
int32 height = 5;
|
||||
bytes colors = 6;
|
||||
}
|
||||
|
||||
message CursorPosition {
|
||||
sint32 x = 1;
|
||||
sint32 y = 2;
|
||||
}
|
||||
|
||||
message Hash {
|
||||
string salt = 1;
|
||||
string challenge = 2;
|
||||
}
|
||||
|
||||
message Clipboard {
|
||||
bool compress = 1;
|
||||
bytes content = 2;
|
||||
}
|
||||
|
||||
enum FileType {
|
||||
Dir = 0;
|
||||
DirLink = 2;
|
||||
DirDrive = 3;
|
||||
File = 4;
|
||||
FileLink = 5;
|
||||
}
|
||||
|
||||
message FileEntry {
|
||||
FileType entry_type = 1;
|
||||
string name = 2;
|
||||
bool is_hidden = 3;
|
||||
uint64 size = 4;
|
||||
uint64 modified_time = 5;
|
||||
}
|
||||
|
||||
message FileDirectory {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
repeated FileEntry entries = 3;
|
||||
}
|
||||
|
||||
message ReadDir {
|
||||
string path = 1;
|
||||
bool include_hidden = 2;
|
||||
}
|
||||
|
||||
message ReadAllFiles {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
bool include_hidden = 3;
|
||||
}
|
||||
|
||||
message FileAction {
|
||||
oneof union {
|
||||
ReadDir read_dir = 1;
|
||||
FileTransferSendRequest send = 2;
|
||||
FileTransferReceiveRequest receive = 3;
|
||||
FileDirCreate create = 4;
|
||||
FileRemoveDir remove_dir = 5;
|
||||
FileRemoveFile remove_file = 6;
|
||||
ReadAllFiles all_files = 7;
|
||||
FileTransferCancel cancel = 8;
|
||||
FileTransferSendConfirmRequest send_confirm = 9;
|
||||
}
|
||||
}
|
||||
|
||||
message FileTransferCancel { int32 id = 1; }
|
||||
|
||||
message FileResponse {
|
||||
oneof union {
|
||||
FileDirectory dir = 1;
|
||||
FileTransferBlock block = 2;
|
||||
FileTransferError error = 3;
|
||||
FileTransferDone done = 4;
|
||||
FileTransferDigest digest = 5;
|
||||
}
|
||||
}
|
||||
|
||||
message FileTransferDigest {
|
||||
int32 id = 1;
|
||||
sint32 file_num = 2;
|
||||
uint64 last_modified = 3;
|
||||
uint64 file_size = 4;
|
||||
bool is_upload = 5;
|
||||
}
|
||||
|
||||
message FileTransferBlock {
|
||||
int32 id = 1;
|
||||
sint32 file_num = 2;
|
||||
bytes data = 3;
|
||||
bool compressed = 4;
|
||||
uint32 blk_id = 5;
|
||||
}
|
||||
|
||||
message FileTransferError {
|
||||
int32 id = 1;
|
||||
string error = 2;
|
||||
sint32 file_num = 3;
|
||||
}
|
||||
|
||||
message FileTransferSendRequest {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
bool include_hidden = 3;
|
||||
int32 file_num = 4;
|
||||
}
|
||||
|
||||
message FileTransferSendConfirmRequest {
|
||||
int32 id = 1;
|
||||
sint32 file_num = 2;
|
||||
oneof union {
|
||||
bool skip = 3;
|
||||
uint32 offset_blk = 4;
|
||||
}
|
||||
}
|
||||
|
||||
message FileTransferDone {
|
||||
int32 id = 1;
|
||||
sint32 file_num = 2;
|
||||
}
|
||||
|
||||
message FileTransferReceiveRequest {
|
||||
int32 id = 1;
|
||||
string path = 2; // path written to
|
||||
repeated FileEntry files = 3;
|
||||
int32 file_num = 4;
|
||||
}
|
||||
|
||||
message FileRemoveDir {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
bool recursive = 3;
|
||||
}
|
||||
|
||||
message FileRemoveFile {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
sint32 file_num = 3;
|
||||
}
|
||||
|
||||
message FileDirCreate {
|
||||
int32 id = 1;
|
||||
string path = 2;
|
||||
}
|
||||
|
||||
// main logic from freeRDP
|
||||
message CliprdrMonitorReady {
|
||||
}
|
||||
|
||||
message CliprdrFormat {
|
||||
int32 id = 2;
|
||||
string format = 3;
|
||||
}
|
||||
|
||||
message CliprdrServerFormatList {
|
||||
repeated CliprdrFormat formats = 2;
|
||||
}
|
||||
|
||||
message CliprdrServerFormatListResponse {
|
||||
int32 msg_flags = 2;
|
||||
}
|
||||
|
||||
message CliprdrServerFormatDataRequest {
|
||||
int32 requested_format_id = 2;
|
||||
}
|
||||
|
||||
message CliprdrServerFormatDataResponse {
|
||||
int32 msg_flags = 2;
|
||||
bytes format_data = 3;
|
||||
}
|
||||
|
||||
message CliprdrFileContentsRequest {
|
||||
int32 stream_id = 2;
|
||||
int32 list_index = 3;
|
||||
int32 dw_flags = 4;
|
||||
int32 n_position_low = 5;
|
||||
int32 n_position_high = 6;
|
||||
int32 cb_requested = 7;
|
||||
bool have_clip_data_id = 8;
|
||||
int32 clip_data_id = 9;
|
||||
}
|
||||
|
||||
message CliprdrFileContentsResponse {
|
||||
int32 msg_flags = 3;
|
||||
int32 stream_id = 4;
|
||||
bytes requested_data = 5;
|
||||
}
|
||||
|
||||
message Cliprdr {
|
||||
oneof union {
|
||||
CliprdrMonitorReady ready = 1;
|
||||
CliprdrServerFormatList format_list = 2;
|
||||
CliprdrServerFormatListResponse format_list_response = 3;
|
||||
CliprdrServerFormatDataRequest format_data_request = 4;
|
||||
CliprdrServerFormatDataResponse format_data_response = 5;
|
||||
CliprdrFileContentsRequest file_contents_request = 6;
|
||||
CliprdrFileContentsResponse file_contents_response = 7;
|
||||
}
|
||||
}
|
||||
|
||||
message SwitchDisplay {
|
||||
int32 display = 1;
|
||||
sint32 x = 2;
|
||||
sint32 y = 3;
|
||||
int32 width = 4;
|
||||
int32 height = 5;
|
||||
bool cursor_embedded = 6;
|
||||
}
|
||||
|
||||
message PermissionInfo {
|
||||
enum Permission {
|
||||
Keyboard = 0;
|
||||
Clipboard = 2;
|
||||
Audio = 3;
|
||||
File = 4;
|
||||
Restart = 5;
|
||||
Recording = 6;
|
||||
}
|
||||
|
||||
Permission permission = 1;
|
||||
bool enabled = 2;
|
||||
}
|
||||
|
||||
enum ImageQuality {
|
||||
NotSet = 0;
|
||||
Low = 2;
|
||||
Balanced = 3;
|
||||
Best = 4;
|
||||
}
|
||||
|
||||
message VideoCodecState {
|
||||
enum PreferCodec {
|
||||
Auto = 0;
|
||||
VPX = 1;
|
||||
H264 = 2;
|
||||
H265 = 3;
|
||||
}
|
||||
|
||||
int32 score_vpx = 1;
|
||||
int32 score_h264 = 2;
|
||||
int32 score_h265 = 3;
|
||||
PreferCodec prefer = 4;
|
||||
}
|
||||
|
||||
message OptionMessage {
|
||||
enum BoolOption {
|
||||
NotSet = 0;
|
||||
No = 1;
|
||||
Yes = 2;
|
||||
}
|
||||
ImageQuality image_quality = 1;
|
||||
BoolOption lock_after_session_end = 2;
|
||||
BoolOption show_remote_cursor = 3;
|
||||
BoolOption privacy_mode = 4;
|
||||
BoolOption block_input = 5;
|
||||
int32 custom_image_quality = 6;
|
||||
BoolOption disable_audio = 7;
|
||||
BoolOption disable_clipboard = 8;
|
||||
BoolOption enable_file_transfer = 9;
|
||||
VideoCodecState video_codec_state = 10;
|
||||
int32 custom_fps = 11;
|
||||
}
|
||||
|
||||
message TestDelay {
|
||||
int64 time = 1;
|
||||
bool from_client = 2;
|
||||
uint32 last_delay = 3;
|
||||
uint32 target_bitrate = 4;
|
||||
}
|
||||
|
||||
message PublicKey {
|
||||
bytes asymmetric_value = 1;
|
||||
bytes symmetric_value = 2;
|
||||
}
|
||||
|
||||
message SignedId { bytes id = 1; }
|
||||
|
||||
message AudioFormat {
|
||||
uint32 sample_rate = 1;
|
||||
uint32 channels = 2;
|
||||
}
|
||||
|
||||
message AudioFrame {
|
||||
bytes data = 1;
|
||||
int64 timestamp = 2;
|
||||
}
|
||||
|
||||
// Notify peer to show message box.
|
||||
message MessageBox {
|
||||
// Message type. Refer to flutter/lib/common.dart/msgBox().
|
||||
string msgtype = 1;
|
||||
string title = 2;
|
||||
// English
|
||||
string text = 3;
|
||||
// If not empty, msgbox provides a button to following the link.
|
||||
// The link here can't be directly http url.
|
||||
// It must be the key of http url configed in peer side or "rustdesk://*" (jump in app).
|
||||
string link = 4;
|
||||
}
|
||||
|
||||
message BackNotification {
|
||||
// no need to consider block input by someone else
|
||||
enum BlockInputState {
|
||||
BlkStateUnknown = 0;
|
||||
BlkOnSucceeded = 2;
|
||||
BlkOnFailed = 3;
|
||||
BlkOffSucceeded = 4;
|
||||
BlkOffFailed = 5;
|
||||
}
|
||||
enum PrivacyModeState {
|
||||
PrvStateUnknown = 0;
|
||||
// Privacy mode on by someone else
|
||||
PrvOnByOther = 2;
|
||||
// Privacy mode is not supported on the remote side
|
||||
PrvNotSupported = 3;
|
||||
// Privacy mode on by self
|
||||
PrvOnSucceeded = 4;
|
||||
// Privacy mode on by self, but denied
|
||||
PrvOnFailedDenied = 5;
|
||||
// Some plugins are not found
|
||||
PrvOnFailedPlugin = 6;
|
||||
// Privacy mode on by self, but failed
|
||||
PrvOnFailed = 7;
|
||||
// Privacy mode off by self
|
||||
PrvOffSucceeded = 8;
|
||||
// Ctrl + P
|
||||
PrvOffByPeer = 9;
|
||||
// Privacy mode off by self, but failed
|
||||
PrvOffFailed = 10;
|
||||
PrvOffUnknown = 11;
|
||||
}
|
||||
|
||||
oneof union {
|
||||
PrivacyModeState privacy_mode_state = 1;
|
||||
BlockInputState block_input_state = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message ElevationRequestWithLogon {
|
||||
string username = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
message ElevationRequest {
|
||||
oneof union {
|
||||
bool direct = 1;
|
||||
ElevationRequestWithLogon logon = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message SwitchSidesRequest {
|
||||
bytes uuid = 1;
|
||||
}
|
||||
|
||||
message SwitchSidesResponse {
|
||||
bytes uuid = 1;
|
||||
LoginRequest lr = 2;
|
||||
}
|
||||
|
||||
message SwitchBack {}
|
||||
|
||||
message Misc {
|
||||
oneof union {
|
||||
ChatMessage chat_message = 4;
|
||||
SwitchDisplay switch_display = 5;
|
||||
PermissionInfo permission_info = 6;
|
||||
OptionMessage option = 7;
|
||||
AudioFormat audio_format = 8;
|
||||
string close_reason = 9;
|
||||
bool refresh_video = 10;
|
||||
bool video_received = 12;
|
||||
BackNotification back_notification = 13;
|
||||
bool restart_remote_device = 14;
|
||||
bool uac = 15;
|
||||
bool foreground_window_elevated = 16;
|
||||
bool stop_service = 17;
|
||||
ElevationRequest elevation_request = 18;
|
||||
string elevation_response = 19;
|
||||
bool portable_service_running = 20;
|
||||
SwitchSidesRequest switch_sides_request = 21;
|
||||
SwitchBack switch_back = 22;
|
||||
}
|
||||
}
|
||||
|
||||
message VoiceCallRequest {
|
||||
int64 req_timestamp = 1;
|
||||
// Indicates whether the request is a connect action or a disconnect action.
|
||||
bool is_connect = 2;
|
||||
}
|
||||
|
||||
message VoiceCallResponse {
|
||||
bool accepted = 1;
|
||||
int64 req_timestamp = 2; // Should copy from [VoiceCallRequest::req_timestamp].
|
||||
int64 ack_timestamp = 3;
|
||||
}
|
||||
|
||||
message Message {
|
||||
oneof union {
|
||||
SignedId signed_id = 3;
|
||||
PublicKey public_key = 4;
|
||||
TestDelay test_delay = 5;
|
||||
VideoFrame video_frame = 6;
|
||||
LoginRequest login_request = 7;
|
||||
LoginResponse login_response = 8;
|
||||
Hash hash = 9;
|
||||
MouseEvent mouse_event = 10;
|
||||
AudioFrame audio_frame = 11;
|
||||
CursorData cursor_data = 12;
|
||||
CursorPosition cursor_position = 13;
|
||||
uint64 cursor_id = 14;
|
||||
KeyEvent key_event = 15;
|
||||
Clipboard clipboard = 16;
|
||||
FileAction file_action = 17;
|
||||
FileResponse file_response = 18;
|
||||
Misc misc = 19;
|
||||
Cliprdr cliprdr = 20;
|
||||
MessageBox message_box = 21;
|
||||
SwitchSidesResponse switch_sides_response = 22;
|
||||
VoiceCallRequest voice_call_request = 23;
|
||||
VoiceCallResponse voice_call_response = 24;
|
||||
}
|
||||
}
|
||||
182
libs/hbb_common/protos/rendezvous.proto
Normal file
182
libs/hbb_common/protos/rendezvous.proto
Normal file
@@ -0,0 +1,182 @@
|
||||
syntax = "proto3";
|
||||
package hbb;
|
||||
|
||||
message RegisterPeer {
|
||||
string id = 1;
|
||||
int32 serial = 2;
|
||||
}
|
||||
|
||||
enum ConnType {
|
||||
DEFAULT_CONN = 0;
|
||||
FILE_TRANSFER = 1;
|
||||
PORT_FORWARD = 2;
|
||||
RDP = 3;
|
||||
}
|
||||
|
||||
message RegisterPeerResponse { bool request_pk = 2; }
|
||||
|
||||
message PunchHoleRequest {
|
||||
string id = 1;
|
||||
NatType nat_type = 2;
|
||||
string licence_key = 3;
|
||||
ConnType conn_type = 4;
|
||||
string token = 5;
|
||||
}
|
||||
|
||||
message PunchHole {
|
||||
bytes socket_addr = 1;
|
||||
string relay_server = 2;
|
||||
NatType nat_type = 3;
|
||||
}
|
||||
|
||||
message TestNatRequest {
|
||||
int32 serial = 1;
|
||||
}
|
||||
|
||||
// per my test, uint/int has no difference in encoding, int not good for negative, use sint for negative
|
||||
message TestNatResponse {
|
||||
int32 port = 1;
|
||||
ConfigUpdate cu = 2; // for mobile
|
||||
}
|
||||
|
||||
enum NatType {
|
||||
UNKNOWN_NAT = 0;
|
||||
ASYMMETRIC = 1;
|
||||
SYMMETRIC = 2;
|
||||
}
|
||||
|
||||
message PunchHoleSent {
|
||||
bytes socket_addr = 1;
|
||||
string id = 2;
|
||||
string relay_server = 3;
|
||||
NatType nat_type = 4;
|
||||
string version = 5;
|
||||
}
|
||||
|
||||
message RegisterPk {
|
||||
string id = 1;
|
||||
bytes uuid = 2;
|
||||
bytes pk = 3;
|
||||
string old_id = 4;
|
||||
}
|
||||
|
||||
message RegisterPkResponse {
|
||||
enum Result {
|
||||
OK = 0;
|
||||
UUID_MISMATCH = 2;
|
||||
ID_EXISTS = 3;
|
||||
TOO_FREQUENT = 4;
|
||||
INVALID_ID_FORMAT = 5;
|
||||
NOT_SUPPORT = 6;
|
||||
SERVER_ERROR = 7;
|
||||
}
|
||||
Result result = 1;
|
||||
}
|
||||
|
||||
message PunchHoleResponse {
|
||||
bytes socket_addr = 1;
|
||||
bytes pk = 2;
|
||||
enum Failure {
|
||||
ID_NOT_EXIST = 0;
|
||||
OFFLINE = 2;
|
||||
LICENSE_MISMATCH = 3;
|
||||
LICENSE_OVERUSE = 4;
|
||||
}
|
||||
Failure failure = 3;
|
||||
string relay_server = 4;
|
||||
oneof union {
|
||||
NatType nat_type = 5;
|
||||
bool is_local = 6;
|
||||
}
|
||||
string other_failure = 7;
|
||||
}
|
||||
|
||||
message ConfigUpdate {
|
||||
int32 serial = 1;
|
||||
repeated string rendezvous_servers = 2;
|
||||
}
|
||||
|
||||
message RequestRelay {
|
||||
string id = 1;
|
||||
string uuid = 2;
|
||||
bytes socket_addr = 3;
|
||||
string relay_server = 4;
|
||||
bool secure = 5;
|
||||
string licence_key = 6;
|
||||
ConnType conn_type = 7;
|
||||
string token = 8;
|
||||
}
|
||||
|
||||
message RelayResponse {
|
||||
bytes socket_addr = 1;
|
||||
string uuid = 2;
|
||||
string relay_server = 3;
|
||||
oneof union {
|
||||
string id = 4;
|
||||
bytes pk = 5;
|
||||
}
|
||||
string refuse_reason = 6;
|
||||
string version = 7;
|
||||
}
|
||||
|
||||
message SoftwareUpdate { string url = 1; }
|
||||
|
||||
// if in same intranet, punch hole won't work both for udp and tcp,
|
||||
// even some router has below connection error if we connect itself,
|
||||
// { kind: Other, error: "could not resolve to any address" },
|
||||
// so we request local address to connect.
|
||||
message FetchLocalAddr {
|
||||
bytes socket_addr = 1;
|
||||
string relay_server = 2;
|
||||
}
|
||||
|
||||
message LocalAddr {
|
||||
bytes socket_addr = 1;
|
||||
bytes local_addr = 2;
|
||||
string relay_server = 3;
|
||||
string id = 4;
|
||||
string version = 5;
|
||||
}
|
||||
|
||||
message PeerDiscovery {
|
||||
string cmd = 1;
|
||||
string mac = 2;
|
||||
string id = 3;
|
||||
string username = 4;
|
||||
string hostname = 5;
|
||||
string platform = 6;
|
||||
string misc = 7;
|
||||
}
|
||||
|
||||
message OnlineRequest {
|
||||
string id = 1;
|
||||
repeated string peers = 2;
|
||||
}
|
||||
|
||||
message OnlineResponse {
|
||||
bytes states = 1;
|
||||
}
|
||||
|
||||
message RendezvousMessage {
|
||||
oneof union {
|
||||
RegisterPeer register_peer = 6;
|
||||
RegisterPeerResponse register_peer_response = 7;
|
||||
PunchHoleRequest punch_hole_request = 8;
|
||||
PunchHole punch_hole = 9;
|
||||
PunchHoleSent punch_hole_sent = 10;
|
||||
PunchHoleResponse punch_hole_response = 11;
|
||||
FetchLocalAddr fetch_local_addr = 12;
|
||||
LocalAddr local_addr = 13;
|
||||
ConfigUpdate configure_update = 14;
|
||||
RegisterPk register_pk = 15;
|
||||
RegisterPkResponse register_pk_response = 16;
|
||||
SoftwareUpdate software_update = 17;
|
||||
RequestRelay request_relay = 18;
|
||||
RelayResponse relay_response = 19;
|
||||
TestNatRequest test_nat_request = 20;
|
||||
TestNatResponse test_nat_response = 21;
|
||||
PeerDiscovery peer_discovery = 22;
|
||||
OnlineRequest online_request = 23;
|
||||
OnlineResponse online_response = 24;
|
||||
}
|
||||
}
|
||||
280
libs/hbb_common/src/bytes_codec.rs
Normal file
280
libs/hbb_common/src/bytes_codec.rs
Normal file
@@ -0,0 +1,280 @@
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
use std::io;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct BytesCodec {
|
||||
state: DecodeState,
|
||||
raw: bool,
|
||||
max_packet_length: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum DecodeState {
|
||||
Head,
|
||||
Data(usize),
|
||||
}
|
||||
|
||||
impl Default for BytesCodec {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl BytesCodec {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: DecodeState::Head,
|
||||
raw: false,
|
||||
max_packet_length: usize::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_raw(&mut self) {
|
||||
self.raw = true;
|
||||
}
|
||||
|
||||
pub fn set_max_packet_length(&mut self, n: usize) {
|
||||
self.max_packet_length = n;
|
||||
}
|
||||
|
||||
fn decode_head(&mut self, src: &mut BytesMut) -> io::Result<Option<usize>> {
|
||||
if src.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let head_len = ((src[0] & 0x3) + 1) as usize;
|
||||
if src.len() < head_len {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut n = src[0] as usize;
|
||||
if head_len > 1 {
|
||||
n |= (src[1] as usize) << 8;
|
||||
}
|
||||
if head_len > 2 {
|
||||
n |= (src[2] as usize) << 16;
|
||||
}
|
||||
if head_len > 3 {
|
||||
n |= (src[3] as usize) << 24;
|
||||
}
|
||||
n >>= 2;
|
||||
if n > self.max_packet_length {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Too big packet"));
|
||||
}
|
||||
src.advance(head_len);
|
||||
src.reserve(n);
|
||||
Ok(Some(n))
|
||||
}
|
||||
|
||||
fn decode_data(&self, n: usize, src: &mut BytesMut) -> io::Result<Option<BytesMut>> {
|
||||
if src.len() < n {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(src.split_to(n)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for BytesCodec {
|
||||
type Item = BytesMut;
|
||||
type Error = io::Error;
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<BytesMut>, io::Error> {
|
||||
if self.raw {
|
||||
if !src.is_empty() {
|
||||
let len = src.len();
|
||||
return Ok(Some(src.split_to(len)));
|
||||
} else {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let n = match self.state {
|
||||
DecodeState::Head => match self.decode_head(src)? {
|
||||
Some(n) => {
|
||||
self.state = DecodeState::Data(n);
|
||||
n
|
||||
}
|
||||
None => return Ok(None),
|
||||
},
|
||||
DecodeState::Data(n) => n,
|
||||
};
|
||||
|
||||
match self.decode_data(n, src)? {
|
||||
Some(data) => {
|
||||
self.state = DecodeState::Head;
|
||||
Ok(Some(data))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoder<Bytes> for BytesCodec {
|
||||
type Error = io::Error;
|
||||
|
||||
fn encode(&mut self, data: Bytes, buf: &mut BytesMut) -> Result<(), io::Error> {
|
||||
if self.raw {
|
||||
buf.reserve(data.len());
|
||||
buf.put(data);
|
||||
return Ok(());
|
||||
}
|
||||
if data.len() <= 0x3F {
|
||||
buf.put_u8((data.len() << 2) as u8);
|
||||
} else if data.len() <= 0x3FFF {
|
||||
buf.put_u16_le((data.len() << 2) as u16 | 0x1);
|
||||
} else if data.len() <= 0x3FFFFF {
|
||||
let h = (data.len() << 2) as u32 | 0x2;
|
||||
buf.put_u16_le((h & 0xFFFF) as u16);
|
||||
buf.put_u8((h >> 16) as u8);
|
||||
} else if data.len() <= 0x3FFFFFFF {
|
||||
buf.put_u32_le((data.len() << 2) as u32 | 0x3);
|
||||
} else {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Overflow"));
|
||||
}
|
||||
buf.extend(data);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_codec1() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
bytes.resize(0x3F, 1);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
let buf_saved = buf.clone();
|
||||
assert_eq!(buf.len(), 0x3F + 1);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3F);
|
||||
assert_eq!(res[0], 1);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
let mut codec2 = BytesCodec::new();
|
||||
let mut buf2 = BytesMut::new();
|
||||
if let Ok(None) = codec2.decode(&mut buf2) {
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
buf2.extend(&buf_saved[0..1]);
|
||||
if let Ok(None) = codec2.decode(&mut buf2) {
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
buf2.extend(&buf_saved[1..]);
|
||||
if let Ok(Some(res)) = codec2.decode(&mut buf2) {
|
||||
assert_eq!(res.len(), 0x3F);
|
||||
assert_eq!(res[0], 1);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codec2() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
assert!(codec.encode("".into(), &mut buf).is_ok());
|
||||
assert_eq!(buf.len(), 1);
|
||||
bytes.resize(0x3F + 1, 2);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
assert_eq!(buf.len(), 0x3F + 2 + 2);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3F + 1);
|
||||
assert_eq!(res[0], 2);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codec3() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
bytes.resize(0x3F - 1, 3);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
assert_eq!(buf.len(), 0x3F + 1 - 1);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3F - 1);
|
||||
assert_eq!(res[0], 3);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn test_codec4() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
bytes.resize(0x3FFF, 4);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
assert_eq!(buf.len(), 0x3FFF + 2);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3FFF);
|
||||
assert_eq!(res[0], 4);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codec5() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
bytes.resize(0x3FFFFF, 5);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
assert_eq!(buf.len(), 0x3FFFFF + 3);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3FFFFF);
|
||||
assert_eq!(res[0], 5);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codec6() {
|
||||
let mut codec = BytesCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
bytes.resize(0x3FFFFF + 1, 6);
|
||||
assert!(codec.encode(bytes.into(), &mut buf).is_ok());
|
||||
let buf_saved = buf.clone();
|
||||
assert_eq!(buf.len(), 0x3FFFFF + 4 + 1);
|
||||
if let Ok(Some(res)) = codec.decode(&mut buf) {
|
||||
assert_eq!(res.len(), 0x3FFFFF + 1);
|
||||
assert_eq!(res[0], 6);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
let mut codec2 = BytesCodec::new();
|
||||
let mut buf2 = BytesMut::new();
|
||||
buf2.extend(&buf_saved[0..1]);
|
||||
if let Ok(None) = codec2.decode(&mut buf2) {
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
buf2.extend(&buf_saved[1..6]);
|
||||
if let Ok(None) = codec2.decode(&mut buf2) {
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
buf2.extend(&buf_saved[6..]);
|
||||
if let Ok(Some(res)) = codec2.decode(&mut buf2) {
|
||||
assert_eq!(res.len(), 0x3FFFFF + 1);
|
||||
assert_eq!(res[0], 6);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
}
|
||||
45
libs/hbb_common/src/compress.rs
Normal file
45
libs/hbb_common/src/compress.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::cell::RefCell;
|
||||
use zstd::block::{Compressor, Decompressor};
|
||||
|
||||
thread_local! {
|
||||
static COMPRESSOR: RefCell<Compressor> = RefCell::new(Compressor::new());
|
||||
static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());
|
||||
}
|
||||
|
||||
/// The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
|
||||
/// which is currently 22. Levels >= 20
|
||||
/// Default level is ZSTD_CLEVEL_DEFAULT==3.
|
||||
/// value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT
|
||||
pub fn compress(data: &[u8], level: i32) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
COMPRESSOR.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
match c.compress(data, level) {
|
||||
Ok(res) => out = res,
|
||||
Err(err) => {
|
||||
crate::log::debug!("Failed to compress: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
pub fn decompress(data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
DECOMPRESSOR.with(|d| {
|
||||
if let Ok(mut d) = d.try_borrow_mut() {
|
||||
const MAX: usize = 1024 * 1024 * 64;
|
||||
const MIN: usize = 1024 * 1024;
|
||||
let mut n = 30 * data.len();
|
||||
n = n.clamp(MIN, MAX);
|
||||
match d.decompress(data, n) {
|
||||
Ok(res) => out = res,
|
||||
Err(err) => {
|
||||
crate::log::debug!("Failed to decompress: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
1349
libs/hbb_common/src/config.rs
Normal file
1349
libs/hbb_common/src/config.rs
Normal file
File diff suppressed because it is too large
Load Diff
839
libs/hbb_common/src/fs.rs
Normal file
839
libs/hbb_common/src/fs.rs
Normal file
@@ -0,0 +1,839 @@
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::prelude::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use tokio::{fs::File, io::*};
|
||||
|
||||
use crate::{bail, get_version_number, message_proto::*, ResultType, Stream};
|
||||
// https://doc.rust-lang.org/std/os/windows/fs/trait.MetadataExt.html
|
||||
use crate::{
|
||||
compress::{compress, decompress},
|
||||
config::{Config, COMPRESS_LEVEL},
|
||||
};
|
||||
|
||||
pub fn read_dir(path: &Path, include_hidden: bool) -> ResultType<FileDirectory> {
|
||||
let mut dir = FileDirectory {
|
||||
path: get_string(path),
|
||||
..Default::default()
|
||||
};
|
||||
#[cfg(windows)]
|
||||
if "/" == &get_string(path) {
|
||||
let drives = unsafe { winapi::um::fileapi::GetLogicalDrives() };
|
||||
for i in 0..32 {
|
||||
if drives & (1 << i) != 0 {
|
||||
let name = format!(
|
||||
"{}:",
|
||||
std::char::from_u32('A' as u32 + i as u32).unwrap_or('A')
|
||||
);
|
||||
dir.entries.push(FileEntry {
|
||||
name,
|
||||
entry_type: FileType::DirDrive.into(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
return Ok(dir);
|
||||
}
|
||||
for entry in path.read_dir()?.flatten() {
|
||||
let p = entry.path();
|
||||
let name = p
|
||||
.file_name()
|
||||
.map(|p| p.to_str().unwrap_or(""))
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut is_hidden = false;
|
||||
let meta;
|
||||
if let Ok(tmp) = std::fs::symlink_metadata(&p) {
|
||||
meta = tmp;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
// docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
|
||||
#[cfg(windows)]
|
||||
if meta.file_attributes() & 0x2 != 0 {
|
||||
is_hidden = true;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
if name.find('.').unwrap_or(usize::MAX) == 0 {
|
||||
is_hidden = true;
|
||||
}
|
||||
if is_hidden && !include_hidden {
|
||||
continue;
|
||||
}
|
||||
let (entry_type, size) = {
|
||||
if p.is_dir() {
|
||||
if meta.file_type().is_symlink() {
|
||||
(FileType::DirLink.into(), 0)
|
||||
} else {
|
||||
(FileType::Dir.into(), 0)
|
||||
}
|
||||
} else if meta.file_type().is_symlink() {
|
||||
(FileType::FileLink.into(), 0)
|
||||
} else {
|
||||
(FileType::File.into(), meta.len())
|
||||
}
|
||||
};
|
||||
let modified_time = meta
|
||||
.modified()
|
||||
.map(|x| {
|
||||
x.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.map(|x| x.as_secs())
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.unwrap_or(0);
|
||||
dir.entries.push(FileEntry {
|
||||
name: get_file_name(&p),
|
||||
entry_type,
|
||||
is_hidden,
|
||||
size,
|
||||
modified_time,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_file_name(p: &Path) -> String {
|
||||
p.file_name()
|
||||
.map(|p| p.to_str().unwrap_or(""))
|
||||
.unwrap_or("")
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_string(path: &Path) -> String {
|
||||
path.to_str().unwrap_or("").to_owned()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_path(path: &str) -> PathBuf {
|
||||
Path::new(path).to_path_buf()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_home_as_string() -> String {
|
||||
get_string(&Config::get_home())
|
||||
}
|
||||
|
||||
fn read_dir_recursive(
|
||||
path: &PathBuf,
|
||||
prefix: &Path,
|
||||
include_hidden: bool,
|
||||
) -> ResultType<Vec<FileEntry>> {
|
||||
let mut files = Vec::new();
|
||||
if path.is_dir() {
|
||||
// to-do: symbol link handling, cp the link rather than the content
|
||||
// to-do: file mode, for unix
|
||||
let fd = read_dir(path, include_hidden)?;
|
||||
for entry in fd.entries.iter() {
|
||||
match entry.entry_type.enum_value() {
|
||||
Ok(FileType::File) => {
|
||||
let mut entry = entry.clone();
|
||||
entry.name = get_string(&prefix.join(entry.name));
|
||||
files.push(entry);
|
||||
}
|
||||
Ok(FileType::Dir) => {
|
||||
if let Ok(mut tmp) = read_dir_recursive(
|
||||
&path.join(&entry.name),
|
||||
&prefix.join(&entry.name),
|
||||
include_hidden,
|
||||
) {
|
||||
for entry in tmp.drain(0..) {
|
||||
files.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
} else if path.is_file() {
|
||||
let (size, modified_time) = if let Ok(meta) = std::fs::metadata(path) {
|
||||
(
|
||||
meta.len(),
|
||||
meta.modified()
|
||||
.map(|x| {
|
||||
x.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.map(|x| x.as_secs())
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.unwrap_or(0),
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
files.push(FileEntry {
|
||||
entry_type: FileType::File.into(),
|
||||
size,
|
||||
modified_time,
|
||||
..Default::default()
|
||||
});
|
||||
Ok(files)
|
||||
} else {
|
||||
bail!("Not exists");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_recursive_files(path: &str, include_hidden: bool) -> ResultType<Vec<FileEntry>> {
|
||||
read_dir_recursive(&get_path(path), &get_path(""), include_hidden)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_file_exists(file_path: &str) -> bool {
|
||||
return Path::new(file_path).exists();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn can_enable_overwrite_detection(version: i64) -> bool {
|
||||
version >= get_version_number("1.1.10")
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TransferJob {
|
||||
pub id: i32,
|
||||
pub remote: String,
|
||||
pub path: PathBuf,
|
||||
pub show_hidden: bool,
|
||||
pub is_remote: bool,
|
||||
pub is_last_job: bool,
|
||||
pub file_num: i32,
|
||||
pub files: Vec<FileEntry>,
|
||||
|
||||
file: Option<File>,
|
||||
total_size: u64,
|
||||
finished_size: u64,
|
||||
transferred: u64,
|
||||
enable_overwrite_detection: bool,
|
||||
file_confirmed: bool,
|
||||
// indicating the last file is skipped
|
||||
file_skipped: bool,
|
||||
file_is_waiting: bool,
|
||||
default_overwrite_strategy: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
pub struct TransferJobMeta {
|
||||
#[serde(default)]
|
||||
pub id: i32,
|
||||
#[serde(default)]
|
||||
pub remote: String,
|
||||
#[serde(default)]
|
||||
pub to: String,
|
||||
#[serde(default)]
|
||||
pub show_hidden: bool,
|
||||
#[serde(default)]
|
||||
pub file_num: i32,
|
||||
#[serde(default)]
|
||||
pub is_remote: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
pub struct RemoveJobMeta {
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
#[serde(default)]
|
||||
pub is_remote: bool,
|
||||
#[serde(default)]
|
||||
pub no_confirm: bool,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_ext(name: &str) -> &str {
|
||||
if let Some(i) = name.rfind('.') {
|
||||
return &name[i + 1..];
|
||||
}
|
||||
""
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_compressed_file(name: &str) -> bool {
|
||||
let ext = get_ext(name);
|
||||
ext == "xz"
|
||||
|| ext == "gz"
|
||||
|| ext == "zip"
|
||||
|| ext == "7z"
|
||||
|| ext == "rar"
|
||||
|| ext == "bz2"
|
||||
|| ext == "tgz"
|
||||
|| ext == "png"
|
||||
|| ext == "jpg"
|
||||
}
|
||||
|
||||
impl TransferJob {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_write(
|
||||
id: i32,
|
||||
remote: String,
|
||||
path: String,
|
||||
file_num: i32,
|
||||
show_hidden: bool,
|
||||
is_remote: bool,
|
||||
files: Vec<FileEntry>,
|
||||
enable_overwrite_detection: bool,
|
||||
) -> Self {
|
||||
log::info!("new write {}", path);
|
||||
let total_size = files.iter().map(|x| x.size).sum();
|
||||
Self {
|
||||
id,
|
||||
remote,
|
||||
path: get_path(&path),
|
||||
file_num,
|
||||
show_hidden,
|
||||
is_remote,
|
||||
files,
|
||||
total_size,
|
||||
enable_overwrite_detection,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_read(
|
||||
id: i32,
|
||||
remote: String,
|
||||
path: String,
|
||||
file_num: i32,
|
||||
show_hidden: bool,
|
||||
is_remote: bool,
|
||||
enable_overwrite_detection: bool,
|
||||
) -> ResultType<Self> {
|
||||
log::info!("new read {}", path);
|
||||
let files = get_recursive_files(&path, show_hidden)?;
|
||||
let total_size = files.iter().map(|x| x.size).sum();
|
||||
Ok(Self {
|
||||
id,
|
||||
remote,
|
||||
path: get_path(&path),
|
||||
file_num,
|
||||
show_hidden,
|
||||
is_remote,
|
||||
files,
|
||||
total_size,
|
||||
enable_overwrite_detection,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn files(&self) -> &Vec<FileEntry> {
|
||||
&self.files
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_files(&mut self, files: Vec<FileEntry>) {
|
||||
self.files = files;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn total_size(&self) -> u64 {
|
||||
self.total_size
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn finished_size(&self) -> u64 {
|
||||
self.finished_size
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn transferred(&self) -> u64 {
|
||||
self.transferred
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn file_num(&self) -> i32 {
|
||||
self.file_num
|
||||
}
|
||||
|
||||
pub fn modify_time(&self) {
|
||||
let file_num = self.file_num as usize;
|
||||
if file_num < self.files.len() {
|
||||
let entry = &self.files[file_num];
|
||||
let path = self.join(&entry.name);
|
||||
let download_path = format!("{}.download", get_string(&path));
|
||||
std::fs::rename(download_path, &path).ok();
|
||||
filetime::set_file_mtime(
|
||||
&path,
|
||||
filetime::FileTime::from_unix_time(entry.modified_time as _, 0),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_download_file(&self) {
|
||||
let file_num = self.file_num as usize;
|
||||
if file_num < self.files.len() {
|
||||
let entry = &self.files[file_num];
|
||||
let path = self.join(&entry.name);
|
||||
let download_path = format!("{}.download", get_string(&path));
|
||||
std::fs::remove_file(download_path).ok();
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn write(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if block.id != self.id {
|
||||
bail!("Wrong id");
|
||||
}
|
||||
let file_num = block.file_num as usize;
|
||||
if file_num >= self.files.len() {
|
||||
bail!("Wrong file number");
|
||||
}
|
||||
if file_num != self.file_num as usize || self.file.is_none() {
|
||||
self.modify_time();
|
||||
if let Some(file) = self.file.as_mut() {
|
||||
file.sync_all().await?;
|
||||
}
|
||||
self.file_num = block.file_num;
|
||||
let entry = &self.files[file_num];
|
||||
let path = self.join(&entry.name);
|
||||
if let Some(p) = path.parent() {
|
||||
std::fs::create_dir_all(p).ok();
|
||||
}
|
||||
let path = format!("{}.download", get_string(&path));
|
||||
self.file = Some(File::create(&path).await?);
|
||||
}
|
||||
if block.compressed {
|
||||
let tmp = decompress(&block.data);
|
||||
self.file.as_mut().unwrap().write_all(&tmp).await?;
|
||||
self.finished_size += tmp.len() as u64;
|
||||
} else {
|
||||
self.file.as_mut().unwrap().write_all(&block.data).await?;
|
||||
self.finished_size += block.data.len() as u64;
|
||||
}
|
||||
self.transferred += block.data.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn join(&self, name: &str) -> PathBuf {
|
||||
if name.is_empty() {
|
||||
self.path.clone()
|
||||
} else {
|
||||
self.path.join(name)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read(&mut self, stream: &mut Stream) -> ResultType<Option<FileTransferBlock>> {
|
||||
let file_num = self.file_num as usize;
|
||||
if file_num >= self.files.len() {
|
||||
self.file.take();
|
||||
return Ok(None);
|
||||
}
|
||||
let name = &self.files[file_num].name;
|
||||
if self.file.is_none() {
|
||||
match File::open(self.join(name)).await {
|
||||
Ok(file) => {
|
||||
self.file = Some(file);
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
}
|
||||
Err(err) => {
|
||||
self.file_num += 1;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.enable_overwrite_detection && !self.file_confirmed() {
|
||||
if !self.file_is_waiting() {
|
||||
self.send_current_digest(stream).await?;
|
||||
self.set_file_is_waiting(true);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
const BUF_SIZE: usize = 128 * 1024;
|
||||
let mut buf: Vec<u8> = vec![0; BUF_SIZE];
|
||||
let mut compressed = false;
|
||||
let mut offset: usize = 0;
|
||||
loop {
|
||||
match self.file.as_mut().unwrap().read(&mut buf[offset..]).await {
|
||||
Err(err) => {
|
||||
self.file_num += 1;
|
||||
self.file = None;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
return Err(err.into());
|
||||
}
|
||||
Ok(n) => {
|
||||
offset += n;
|
||||
if n == 0 || offset == BUF_SIZE {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe { buf.set_len(offset) };
|
||||
if offset == 0 {
|
||||
self.file_num += 1;
|
||||
self.file = None;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
} else {
|
||||
self.finished_size += offset as u64;
|
||||
if !is_compressed_file(name) {
|
||||
let tmp = compress(&buf, COMPRESS_LEVEL);
|
||||
if tmp.len() < buf.len() {
|
||||
buf = tmp;
|
||||
compressed = true;
|
||||
}
|
||||
}
|
||||
self.transferred += buf.len() as u64;
|
||||
}
|
||||
Ok(Some(FileTransferBlock {
|
||||
id: self.id,
|
||||
file_num: file_num as _,
|
||||
data: buf.into(),
|
||||
compressed,
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
|
||||
async fn send_current_digest(&mut self, stream: &mut Stream) -> ResultType<()> {
|
||||
let mut msg = Message::new();
|
||||
let mut resp = FileResponse::new();
|
||||
let meta = self.file.as_ref().unwrap().metadata().await?;
|
||||
let last_modified = meta
|
||||
.modified()?
|
||||
.duration_since(SystemTime::UNIX_EPOCH)?
|
||||
.as_secs();
|
||||
resp.set_digest(FileTransferDigest {
|
||||
id: self.id,
|
||||
file_num: self.file_num,
|
||||
last_modified,
|
||||
file_size: meta.len(),
|
||||
..Default::default()
|
||||
});
|
||||
msg.set_file_response(resp);
|
||||
stream.send(&msg).await?;
|
||||
log::info!(
|
||||
"id: {}, file_num:{}, digest message is sent. waiting for confirm. msg: {:?}",
|
||||
self.id,
|
||||
self.file_num,
|
||||
msg
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_overwrite_strategy(&mut self, overwrite_strategy: Option<bool>) {
|
||||
self.default_overwrite_strategy = overwrite_strategy;
|
||||
}
|
||||
|
||||
pub fn default_overwrite_strategy(&self) -> Option<bool> {
|
||||
self.default_overwrite_strategy
|
||||
}
|
||||
|
||||
pub fn set_file_confirmed(&mut self, file_confirmed: bool) {
|
||||
log::info!("id: {}, file_confirmed: {}", self.id, file_confirmed);
|
||||
self.file_confirmed = file_confirmed;
|
||||
self.file_skipped = false;
|
||||
}
|
||||
|
||||
pub fn set_file_is_waiting(&mut self, file_is_waiting: bool) {
|
||||
self.file_is_waiting = file_is_waiting;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn file_is_waiting(&self) -> bool {
|
||||
self.file_is_waiting
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn file_confirmed(&self) -> bool {
|
||||
self.file_confirmed
|
||||
}
|
||||
|
||||
/// Indicating whether the last file is skipped
|
||||
#[inline]
|
||||
pub fn file_skipped(&self) -> bool {
|
||||
self.file_skipped
|
||||
}
|
||||
|
||||
/// Indicating whether the whole task is skipped
|
||||
#[inline]
|
||||
pub fn job_skipped(&self) -> bool {
|
||||
self.file_skipped() && self.files.len() == 1
|
||||
}
|
||||
|
||||
/// Check whether the job is completed after `read` returns `None`
|
||||
/// This is a helper function which gives additional lifecycle when the job reads `None`.
|
||||
/// If returns `true`, it means we can delete the job automatically. `False` otherwise.
|
||||
///
|
||||
/// [`Note`]
|
||||
/// Conditions:
|
||||
/// 1. Files are not waiting for confirmation by peers.
|
||||
#[inline]
|
||||
pub fn job_completed(&self) -> bool {
|
||||
// has no error, Condition 2
|
||||
!self.enable_overwrite_detection || (!self.file_confirmed && !self.file_is_waiting)
|
||||
}
|
||||
|
||||
/// Get job error message, useful for getting status when job had finished
|
||||
pub fn job_error(&self) -> Option<String> {
|
||||
if self.job_skipped() {
|
||||
return Some("skipped".to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn set_file_skipped(&mut self) -> bool {
|
||||
log::debug!("skip file {} in job {}", self.file_num, self.id);
|
||||
self.file.take();
|
||||
self.set_file_confirmed(false);
|
||||
self.set_file_is_waiting(false);
|
||||
self.file_num += 1;
|
||||
self.file_skipped = true;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
|
||||
if self.file_num() != r.file_num {
|
||||
log::info!("file num truncated, ignoring");
|
||||
} else {
|
||||
match r.union {
|
||||
Some(file_transfer_send_confirm_request::Union::Skip(s)) => {
|
||||
if s {
|
||||
self.set_file_skipped();
|
||||
} else {
|
||||
self.set_file_confirmed(true);
|
||||
}
|
||||
}
|
||||
Some(file_transfer_send_confirm_request::Union::OffsetBlk(_offset)) => {
|
||||
self.set_file_confirmed(true);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn gen_meta(&self) -> TransferJobMeta {
|
||||
TransferJobMeta {
|
||||
id: self.id,
|
||||
remote: self.remote.to_string(),
|
||||
to: self.path.to_string_lossy().to_string(),
|
||||
file_num: self.file_num,
|
||||
show_hidden: self.show_hidden,
|
||||
is_remote: self.is_remote,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_error<T: std::string::ToString>(id: i32, err: T, file_num: i32) -> Message {
|
||||
let mut resp = FileResponse::new();
|
||||
resp.set_error(FileTransferError {
|
||||
id,
|
||||
error: err.to_string(),
|
||||
file_num,
|
||||
..Default::default()
|
||||
});
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_response(resp);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_dir(id: i32, path: String, files: Vec<FileEntry>) -> Message {
|
||||
let mut resp = FileResponse::new();
|
||||
resp.set_dir(FileDirectory {
|
||||
id,
|
||||
path,
|
||||
entries: files,
|
||||
..Default::default()
|
||||
});
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_response(resp);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_block(block: FileTransferBlock) -> Message {
|
||||
let mut resp = FileResponse::new();
|
||||
resp.set_block(block);
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_response(resp);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_send_confirm(r: FileTransferSendConfirmRequest) -> Message {
|
||||
let mut msg_out = Message::new();
|
||||
let mut action = FileAction::new();
|
||||
action.set_send_confirm(r);
|
||||
msg_out.set_file_action(action);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_receive(id: i32, path: String, file_num: i32, files: Vec<FileEntry>) -> Message {
|
||||
let mut action = FileAction::new();
|
||||
action.set_receive(FileTransferReceiveRequest {
|
||||
id,
|
||||
path,
|
||||
files,
|
||||
file_num,
|
||||
..Default::default()
|
||||
});
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_action(action);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_send(id: i32, path: String, file_num: i32, include_hidden: bool) -> Message {
|
||||
log::info!("new send: {},id : {}", path, id);
|
||||
let mut action = FileAction::new();
|
||||
action.set_send(FileTransferSendRequest {
|
||||
id,
|
||||
path,
|
||||
include_hidden,
|
||||
file_num,
|
||||
..Default::default()
|
||||
});
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_action(action);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_done(id: i32, file_num: i32) -> Message {
|
||||
let mut resp = FileResponse::new();
|
||||
resp.set_done(FileTransferDone {
|
||||
id,
|
||||
file_num,
|
||||
..Default::default()
|
||||
});
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_file_response(resp);
|
||||
msg_out
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn remove_job(id: i32, jobs: &mut Vec<TransferJob>) {
|
||||
*jobs = jobs.drain(0..).filter(|x| x.id() != id).collect();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_job(id: i32, jobs: &mut [TransferJob]) -> Option<&mut TransferJob> {
|
||||
jobs.iter_mut().find(|x| x.id() == id)
|
||||
}
|
||||
|
||||
pub async fn handle_read_jobs(
|
||||
jobs: &mut Vec<TransferJob>,
|
||||
stream: &mut crate::Stream,
|
||||
) -> ResultType<()> {
|
||||
let mut finished = Vec::new();
|
||||
for job in jobs.iter_mut() {
|
||||
if job.is_last_job {
|
||||
continue;
|
||||
}
|
||||
match job.read(stream).await {
|
||||
Err(err) => {
|
||||
stream
|
||||
.send(&new_error(job.id(), err, job.file_num()))
|
||||
.await?;
|
||||
}
|
||||
Ok(Some(block)) => {
|
||||
stream.send(&new_block(block)).await?;
|
||||
}
|
||||
Ok(None) => {
|
||||
if job.job_completed() {
|
||||
finished.push(job.id());
|
||||
let err = job.job_error();
|
||||
if err.is_some() {
|
||||
stream
|
||||
.send(&new_error(job.id(), err.unwrap(), job.file_num()))
|
||||
.await?;
|
||||
} else {
|
||||
stream.send(&new_done(job.id(), job.file_num())).await?;
|
||||
}
|
||||
} else {
|
||||
// waiting confirmation.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in finished {
|
||||
remove_job(id, jobs);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_all_empty_dir(path: &PathBuf) -> ResultType<()> {
|
||||
let fd = read_dir(path, true)?;
|
||||
for entry in fd.entries.iter() {
|
||||
match entry.entry_type.enum_value() {
|
||||
Ok(FileType::Dir) => {
|
||||
remove_all_empty_dir(&path.join(&entry.name)).ok();
|
||||
}
|
||||
Ok(FileType::DirLink) | Ok(FileType::FileLink) => {
|
||||
std::fs::remove_file(path.join(&entry.name)).ok();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir(path).ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn remove_file(file: &str) -> ResultType<()> {
|
||||
std::fs::remove_file(get_path(file))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn create_dir(dir: &str) -> ResultType<()> {
|
||||
std::fs::create_dir_all(get_path(dir))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn transform_windows_path(entries: &mut Vec<FileEntry>) {
|
||||
for entry in entries {
|
||||
entry.name = entry.name.replace('\\', "/");
|
||||
}
|
||||
}
|
||||
|
||||
pub enum DigestCheckResult {
|
||||
IsSame,
|
||||
NeedConfirm(FileTransferDigest),
|
||||
NoSuchFile,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_write_need_confirmation(
|
||||
file_path: &str,
|
||||
digest: &FileTransferDigest,
|
||||
) -> ResultType<DigestCheckResult> {
|
||||
let path = Path::new(file_path);
|
||||
if path.exists() && path.is_file() {
|
||||
let metadata = std::fs::metadata(path)?;
|
||||
let modified_time = metadata.modified()?;
|
||||
let remote_mt = Duration::from_secs(digest.last_modified);
|
||||
let local_mt = modified_time.duration_since(UNIX_EPOCH)?;
|
||||
if remote_mt == local_mt && digest.file_size == metadata.len() {
|
||||
return Ok(DigestCheckResult::IsSame);
|
||||
}
|
||||
Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
|
||||
id: digest.id,
|
||||
file_num: digest.file_num,
|
||||
last_modified: local_mt.as_secs(),
|
||||
file_size: metadata.len(),
|
||||
..Default::default()
|
||||
}))
|
||||
} else {
|
||||
Ok(DigestCheckResult::NoSuchFile)
|
||||
}
|
||||
}
|
||||
39
libs/hbb_common/src/keyboard.rs
Normal file
39
libs/hbb_common/src/keyboard.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use std::{fmt, slice::Iter, str::FromStr};
|
||||
|
||||
use crate::protos::message::KeyboardMode;
|
||||
|
||||
impl fmt::Display for KeyboardMode {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
KeyboardMode::Legacy => write!(f, "legacy"),
|
||||
KeyboardMode::Map => write!(f, "map"),
|
||||
KeyboardMode::Translate => write!(f, "translate"),
|
||||
KeyboardMode::Auto => write!(f, "auto"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for KeyboardMode {
|
||||
type Err = ();
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"legacy" => Ok(KeyboardMode::Legacy),
|
||||
"map" => Ok(KeyboardMode::Map),
|
||||
"translate" => Ok(KeyboardMode::Translate),
|
||||
"auto" => Ok(KeyboardMode::Auto),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyboardMode {
|
||||
pub fn iter() -> Iter<'static, KeyboardMode> {
|
||||
static KEYBOARD_MODES: [KeyboardMode; 4] = [
|
||||
KeyboardMode::Legacy,
|
||||
KeyboardMode::Map,
|
||||
KeyboardMode::Translate,
|
||||
KeyboardMode::Auto,
|
||||
];
|
||||
KEYBOARD_MODES.iter()
|
||||
}
|
||||
}
|
||||
391
libs/hbb_common/src/lib.rs
Normal file
391
libs/hbb_common/src/lib.rs
Normal file
@@ -0,0 +1,391 @@
|
||||
pub mod compress;
|
||||
pub mod platform;
|
||||
pub mod protos;
|
||||
pub use bytes;
|
||||
use config::Config;
|
||||
pub use futures;
|
||||
pub use protobuf;
|
||||
pub use protos::message as message_proto;
|
||||
pub use protos::rendezvous as rendezvous_proto;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, BufRead},
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
path::Path,
|
||||
time::{self, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
pub use tokio;
|
||||
pub use tokio_util;
|
||||
pub mod socket_client;
|
||||
pub mod tcp;
|
||||
pub mod udp;
|
||||
pub use env_logger;
|
||||
pub use log;
|
||||
pub mod bytes_codec;
|
||||
#[cfg(feature = "quic")]
|
||||
pub mod quic;
|
||||
pub use anyhow::{self, bail};
|
||||
pub use futures_util;
|
||||
pub mod config;
|
||||
pub mod fs;
|
||||
pub use lazy_static;
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
pub use mac_address;
|
||||
pub use rand;
|
||||
pub use regex;
|
||||
pub use sodiumoxide;
|
||||
pub use tokio_socks;
|
||||
pub use tokio_socks::IntoTargetAddr;
|
||||
pub use tokio_socks::TargetAddr;
|
||||
pub mod password_security;
|
||||
pub use chrono;
|
||||
pub use directories_next;
|
||||
pub mod keyboard;
|
||||
|
||||
#[cfg(feature = "quic")]
|
||||
pub type Stream = quic::Connection;
|
||||
#[cfg(not(feature = "quic"))]
|
||||
pub type Stream = tcp::FramedStream;
|
||||
|
||||
#[inline]
|
||||
pub async fn sleep(sec: f32) {
|
||||
tokio::time::sleep(time::Duration::from_secs_f32(sec)).await;
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! allow_err {
|
||||
($e:expr) => {
|
||||
if let Err(err) = $e {
|
||||
log::debug!(
|
||||
"{:?}, {}:{}:{}:{}",
|
||||
err,
|
||||
module_path!(),
|
||||
file!(),
|
||||
line!(),
|
||||
column!()
|
||||
);
|
||||
} else {
|
||||
}
|
||||
};
|
||||
|
||||
($e:expr, $($arg:tt)*) => {
|
||||
if let Err(err) = $e {
|
||||
log::debug!(
|
||||
"{:?}, {}, {}:{}:{}:{}",
|
||||
err,
|
||||
format_args!($($arg)*),
|
||||
module_path!(),
|
||||
file!(),
|
||||
line!(),
|
||||
column!()
|
||||
);
|
||||
} else {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn timeout<T: std::future::Future>(ms: u64, future: T) -> tokio::time::Timeout<T> {
|
||||
tokio::time::timeout(std::time::Duration::from_millis(ms), future)
|
||||
}
|
||||
|
||||
pub type ResultType<F, E = anyhow::Error> = anyhow::Result<F, E>;
|
||||
|
||||
/// Certain router and firewalls scan the packet and if they
|
||||
/// find an IP address belonging to their pool that they use to do the NAT mapping/translation, so here we mangle the ip address
|
||||
|
||||
pub struct AddrMangle();
|
||||
|
||||
#[inline]
|
||||
pub fn try_into_v4(addr: SocketAddr) -> SocketAddr {
|
||||
match addr {
|
||||
SocketAddr::V6(v6) if !addr.ip().is_loopback() => {
|
||||
if let Some(v4) = v6.ip().to_ipv4() {
|
||||
SocketAddr::new(IpAddr::V4(v4), addr.port())
|
||||
} else {
|
||||
addr
|
||||
}
|
||||
}
|
||||
_ => addr,
|
||||
}
|
||||
}
|
||||
|
||||
impl AddrMangle {
|
||||
pub fn encode(addr: SocketAddr) -> Vec<u8> {
|
||||
// not work with [:1]:<port>
|
||||
let addr = try_into_v4(addr);
|
||||
match addr {
|
||||
SocketAddr::V4(addr_v4) => {
|
||||
let tm = (SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_micros() as u32) as u128;
|
||||
let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
|
||||
let port = addr.port() as u128;
|
||||
let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
|
||||
let bytes = v.to_le_bytes();
|
||||
let mut n_padding = 0;
|
||||
for i in bytes.iter().rev() {
|
||||
if i == &0u8 {
|
||||
n_padding += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
bytes[..(16 - n_padding)].to_vec()
|
||||
}
|
||||
SocketAddr::V6(addr_v6) => {
|
||||
let mut x = addr_v6.ip().octets().to_vec();
|
||||
let port: [u8; 2] = addr_v6.port().to_le_bytes();
|
||||
x.push(port[0]);
|
||||
x.push(port[1]);
|
||||
x
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> SocketAddr {
|
||||
use std::convert::TryInto;
|
||||
|
||||
if bytes.len() > 16 {
|
||||
if bytes.len() != 18 {
|
||||
return Config::get_any_listen_addr(false);
|
||||
}
|
||||
let tmp: [u8; 2] = bytes[16..].try_into().unwrap();
|
||||
let port = u16::from_le_bytes(tmp);
|
||||
let tmp: [u8; 16] = bytes[..16].try_into().unwrap();
|
||||
let ip = std::net::Ipv6Addr::from(tmp);
|
||||
return SocketAddr::new(IpAddr::V6(ip), port);
|
||||
}
|
||||
let mut padded = [0u8; 16];
|
||||
padded[..bytes.len()].copy_from_slice(bytes);
|
||||
let number = u128::from_le_bytes(padded);
|
||||
let tm = (number >> 17) & (u32::max_value() as u128);
|
||||
let ip = (((number >> 49) - tm) as u32).to_le_bytes();
|
||||
let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
|
||||
SocketAddr::V4(SocketAddrV4::new(
|
||||
Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
|
||||
port as u16,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_version_from_url(url: &str) -> String {
|
||||
let n = url.chars().count();
|
||||
let a = url.chars().rev().position(|x| x == '-');
|
||||
if let Some(a) = a {
|
||||
let b = url.chars().rev().position(|x| x == '.');
|
||||
if let Some(b) = b {
|
||||
if a > b {
|
||||
if url
|
||||
.chars()
|
||||
.skip(n - b)
|
||||
.collect::<String>()
|
||||
.parse::<i32>()
|
||||
.is_ok()
|
||||
{
|
||||
return url.chars().skip(n - a).collect();
|
||||
} else {
|
||||
return url.chars().skip(n - a).take(a - b - 1).collect();
|
||||
}
|
||||
} else {
|
||||
return url.chars().skip(n - a).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
"".to_owned()
|
||||
}
|
||||
|
||||
pub fn gen_version() {
|
||||
println!("cargo:rerun-if-changed=Cargo.toml");
|
||||
use std::io::prelude::*;
|
||||
let mut file = File::create("./src/version.rs").unwrap();
|
||||
for line in read_lines("Cargo.toml").unwrap().flatten() {
|
||||
let ab: Vec<&str> = line.split('=').map(|x| x.trim()).collect();
|
||||
if ab.len() == 2 && ab[0] == "version" {
|
||||
file.write_all(format!("pub const VERSION: &str = {};\n", ab[1]).as_bytes())
|
||||
.ok();
|
||||
break;
|
||||
}
|
||||
}
|
||||
// generate build date
|
||||
let build_date = format!("{}", chrono::Local::now().format("%Y-%m-%d %H:%M"));
|
||||
file.write_all(
|
||||
format!("#[allow(dead_code)]\npub const BUILD_DATE: &str = \"{build_date}\";\n").as_bytes(),
|
||||
)
|
||||
.ok();
|
||||
file.sync_all().ok();
|
||||
}
|
||||
|
||||
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let file = File::open(filename)?;
|
||||
Ok(io::BufReader::new(file).lines())
|
||||
}
|
||||
|
||||
pub fn is_valid_custom_id(id: &str) -> bool {
|
||||
regex::Regex::new(r"^[a-zA-Z]\w{5,15}$")
|
||||
.unwrap()
|
||||
.is_match(id)
|
||||
}
|
||||
|
||||
pub fn get_version_number(v: &str) -> i64 {
|
||||
let mut n = 0;
|
||||
for x in v.split('.') {
|
||||
n = n * 1000 + x.parse::<i64>().unwrap_or(0);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
pub fn get_modified_time(path: &std::path::Path) -> SystemTime {
|
||||
std::fs::metadata(path)
|
||||
.map(|m| m.modified().unwrap_or(UNIX_EPOCH))
|
||||
.unwrap_or(UNIX_EPOCH)
|
||||
}
|
||||
|
||||
pub fn get_created_time(path: &std::path::Path) -> SystemTime {
|
||||
std::fs::metadata(path)
|
||||
.map(|m| m.created().unwrap_or(UNIX_EPOCH))
|
||||
.unwrap_or(UNIX_EPOCH)
|
||||
}
|
||||
|
||||
pub fn get_exe_time() -> SystemTime {
|
||||
std::env::current_exe().map_or(UNIX_EPOCH, |path| {
|
||||
let m = get_modified_time(&path);
|
||||
let c = get_created_time(&path);
|
||||
if m > c {
|
||||
m
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_uuid() -> Vec<u8> {
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if let Ok(id) = machine_uid::get() {
|
||||
return id.into();
|
||||
}
|
||||
Config::get_key_pair().1
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_time() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0) as _
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_ipv4_str(id: &str) -> bool {
|
||||
regex::Regex::new(r"^\d+\.\d+\.\d+\.\d+(:\d+)?$")
|
||||
.unwrap()
|
||||
.is_match(id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_ipv6_str(id: &str) -> bool {
|
||||
regex::Regex::new(r"^((([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4})|(\[([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4}\]:\d+))$")
|
||||
.unwrap()
|
||||
.is_match(id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_ip_str(id: &str) -> bool {
|
||||
is_ipv4_str(id) || is_ipv6_str(id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_domain_port_str(id: &str) -> bool {
|
||||
// modified regex for RFC1123 hostname. check https://stackoverflow.com/a/106223 for original version for hostname.
|
||||
// according to [TLD List](https://data.iana.org/TLD/tlds-alpha-by-domain.txt) version 2023011700,
|
||||
// there is no digits in TLD, and length is 2~63.
|
||||
regex::Regex::new(
|
||||
r"(?i)^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z-]{0,61}[a-z]:\d{1,5}$",
|
||||
)
|
||||
.unwrap()
|
||||
.is_match(id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_mangle() {
|
||||
let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 16, 32), 21116));
|
||||
assert_eq!(addr, AddrMangle::decode(&AddrMangle::encode(addr)));
|
||||
|
||||
let addr = "[2001:db8::1]:8080".parse::<SocketAddr>().unwrap();
|
||||
assert_eq!(addr, AddrMangle::decode(&AddrMangle::encode(addr)));
|
||||
|
||||
let addr = "[2001:db8:ff::1111]:80".parse::<SocketAddr>().unwrap();
|
||||
assert_eq!(addr, AddrMangle::decode(&AddrMangle::encode(addr)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_allow_err() {
|
||||
allow_err!(Err("test err") as Result<(), &str>);
|
||||
allow_err!(
|
||||
Err("test err with msg") as Result<(), &str>,
|
||||
"prompt {}",
|
||||
"failed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ipv6() {
|
||||
assert!(is_ipv6_str("1:2:3"));
|
||||
assert!(is_ipv6_str("[ab:2:3]:12"));
|
||||
assert!(is_ipv6_str("[ABEF:2a:3]:12"));
|
||||
assert!(!is_ipv6_str("[ABEG:2a:3]:12"));
|
||||
assert!(!is_ipv6_str("1[ab:2:3]:12"));
|
||||
assert!(!is_ipv6_str("1.1.1.1"));
|
||||
assert!(is_ip_str("1.1.1.1"));
|
||||
assert!(!is_ipv6_str("1:2:"));
|
||||
assert!(is_ipv6_str("1:2::0"));
|
||||
assert!(is_ipv6_str("[1:2::0]:1"));
|
||||
assert!(!is_ipv6_str("[1:2::0]:"));
|
||||
assert!(!is_ipv6_str("1:2::0]:1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hostname_port() {
|
||||
assert!(!is_domain_port_str("a:12"));
|
||||
assert!(!is_domain_port_str("a.b.c:12"));
|
||||
assert!(is_domain_port_str("test.com:12"));
|
||||
assert!(is_domain_port_str("test-UPPER.com:12"));
|
||||
assert!(is_domain_port_str("some-other.domain.com:12"));
|
||||
assert!(!is_domain_port_str("under_score:12"));
|
||||
assert!(!is_domain_port_str("a@bc:12"));
|
||||
assert!(!is_domain_port_str("1.1.1.1:12"));
|
||||
assert!(!is_domain_port_str("1.2.3:12"));
|
||||
assert!(!is_domain_port_str("1.2.3.45:12"));
|
||||
assert!(!is_domain_port_str("a.b.c:123456"));
|
||||
assert!(!is_domain_port_str("---:12"));
|
||||
assert!(!is_domain_port_str(".:12"));
|
||||
// todo: should we also check for these edge cases?
|
||||
// out-of-range port
|
||||
assert!(is_domain_port_str("test.com:0"));
|
||||
assert!(is_domain_port_str("test.com:98989"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mangle2() {
|
||||
let addr = "[::ffff:127.0.0.1]:8080".parse().unwrap();
|
||||
let addr_v4 = "127.0.0.1:8080".parse().unwrap();
|
||||
assert_eq!(AddrMangle::decode(&AddrMangle::encode(addr)), addr_v4);
|
||||
assert_eq!(
|
||||
AddrMangle::decode(&AddrMangle::encode("[::127.0.0.1]:8080".parse().unwrap())),
|
||||
addr_v4
|
||||
);
|
||||
assert_eq!(AddrMangle::decode(&AddrMangle::encode(addr_v4)), addr_v4);
|
||||
let addr_v6 = "[ef::fe]:8080".parse().unwrap();
|
||||
assert_eq!(AddrMangle::decode(&AddrMangle::encode(addr_v6)), addr_v6);
|
||||
let addr_v6 = "[::1]:8080".parse().unwrap();
|
||||
assert_eq!(AddrMangle::decode(&AddrMangle::encode(addr_v6)), addr_v6);
|
||||
}
|
||||
}
|
||||
242
libs/hbb_common/src/password_security.rs
Normal file
242
libs/hbb_common/src/password_security.rs
Normal file
@@ -0,0 +1,242 @@
|
||||
use crate::config::Config;
|
||||
use sodiumoxide::base64;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref TEMPORARY_PASSWORD:Arc<RwLock<String>> = Arc::new(RwLock::new(Config::get_auto_password(temporary_password_length())));
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum VerificationMethod {
|
||||
OnlyUseTemporaryPassword,
|
||||
OnlyUsePermanentPassword,
|
||||
UseBothPasswords,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ApproveMode {
|
||||
Both,
|
||||
Password,
|
||||
Click,
|
||||
}
|
||||
|
||||
// Should only be called in server
|
||||
pub fn update_temporary_password() {
|
||||
*TEMPORARY_PASSWORD.write().unwrap() = Config::get_auto_password(temporary_password_length());
|
||||
}
|
||||
|
||||
// Should only be called in server
|
||||
pub fn temporary_password() -> String {
|
||||
TEMPORARY_PASSWORD.read().unwrap().clone()
|
||||
}
|
||||
|
||||
fn verification_method() -> VerificationMethod {
|
||||
let method = Config::get_option("verification-method");
|
||||
if method == "use-temporary-password" {
|
||||
VerificationMethod::OnlyUseTemporaryPassword
|
||||
} else if method == "use-permanent-password" {
|
||||
VerificationMethod::OnlyUsePermanentPassword
|
||||
} else {
|
||||
VerificationMethod::UseBothPasswords // default
|
||||
}
|
||||
}
|
||||
|
||||
pub fn temporary_password_length() -> usize {
|
||||
let length = Config::get_option("temporary-password-length");
|
||||
if length == "8" {
|
||||
8
|
||||
} else if length == "10" {
|
||||
10
|
||||
} else {
|
||||
6 // default
|
||||
}
|
||||
}
|
||||
|
||||
pub fn temporary_enabled() -> bool {
|
||||
verification_method() != VerificationMethod::OnlyUsePermanentPassword
|
||||
}
|
||||
|
||||
pub fn permanent_enabled() -> bool {
|
||||
verification_method() != VerificationMethod::OnlyUseTemporaryPassword
|
||||
}
|
||||
|
||||
pub fn has_valid_password() -> bool {
|
||||
temporary_enabled() && !temporary_password().is_empty()
|
||||
|| permanent_enabled() && !Config::get_permanent_password().is_empty()
|
||||
}
|
||||
|
||||
pub fn approve_mode() -> ApproveMode {
|
||||
let mode = Config::get_option("approve-mode");
|
||||
if mode == "password" {
|
||||
ApproveMode::Password
|
||||
} else if mode == "click" {
|
||||
ApproveMode::Click
|
||||
} else {
|
||||
ApproveMode::Both
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hide_cm() -> bool {
|
||||
approve_mode() == ApproveMode::Password
|
||||
&& verification_method() == VerificationMethod::OnlyUsePermanentPassword
|
||||
&& !Config::get_option("allow-hide-cm").is_empty()
|
||||
}
|
||||
|
||||
const VERSION_LEN: usize = 2;
|
||||
|
||||
pub fn encrypt_str_or_original(s: &str, version: &str) -> String {
|
||||
if decrypt_str_or_original(s, version).1 {
|
||||
log::error!("Duplicate encryption!");
|
||||
return s.to_owned();
|
||||
}
|
||||
if version == "00" {
|
||||
if let Ok(s) = encrypt(s.as_bytes()) {
|
||||
return version.to_owned() + &s;
|
||||
}
|
||||
}
|
||||
s.to_owned()
|
||||
}
|
||||
|
||||
// String: password
|
||||
// bool: whether decryption is successful
|
||||
// bool: whether should store to re-encrypt when load
|
||||
pub fn decrypt_str_or_original(s: &str, current_version: &str) -> (String, bool, bool) {
|
||||
if s.len() > VERSION_LEN {
|
||||
let version = &s[..VERSION_LEN];
|
||||
if version == "00" {
|
||||
if let Ok(v) = decrypt(s[VERSION_LEN..].as_bytes()) {
|
||||
return (
|
||||
String::from_utf8_lossy(&v).to_string(),
|
||||
true,
|
||||
version != current_version,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(s.to_owned(), false, !s.is_empty())
|
||||
}
|
||||
|
||||
pub fn encrypt_vec_or_original(v: &[u8], version: &str) -> Vec<u8> {
|
||||
if decrypt_vec_or_original(v, version).1 {
|
||||
log::error!("Duplicate encryption!");
|
||||
return v.to_owned();
|
||||
}
|
||||
if version == "00" {
|
||||
if let Ok(s) = encrypt(v) {
|
||||
let mut version = version.to_owned().into_bytes();
|
||||
version.append(&mut s.into_bytes());
|
||||
return version;
|
||||
}
|
||||
}
|
||||
v.to_owned()
|
||||
}
|
||||
|
||||
// Vec<u8>: password
|
||||
// bool: whether decryption is successful
|
||||
// bool: whether should store to re-encrypt when load
|
||||
pub fn decrypt_vec_or_original(v: &[u8], current_version: &str) -> (Vec<u8>, bool, bool) {
|
||||
if v.len() > VERSION_LEN {
|
||||
let version = String::from_utf8_lossy(&v[..VERSION_LEN]);
|
||||
if version == "00" {
|
||||
if let Ok(v) = decrypt(&v[VERSION_LEN..]) {
|
||||
return (v, true, version != current_version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(v.to_owned(), false, !v.is_empty())
|
||||
}
|
||||
|
||||
fn encrypt(v: &[u8]) -> Result<String, ()> {
|
||||
if !v.is_empty() {
|
||||
symmetric_crypt(v, true).map(|v| base64::encode(v, base64::Variant::Original))
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn decrypt(v: &[u8]) -> Result<Vec<u8>, ()> {
|
||||
if !v.is_empty() {
|
||||
base64::decode(v, base64::Variant::Original).and_then(|v| symmetric_crypt(&v, false))
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn symmetric_crypt(data: &[u8], encrypt: bool) -> Result<Vec<u8>, ()> {
|
||||
use sodiumoxide::crypto::secretbox;
|
||||
use std::convert::TryInto;
|
||||
|
||||
let mut keybuf = crate::get_uuid();
|
||||
keybuf.resize(secretbox::KEYBYTES, 0);
|
||||
let key = secretbox::Key(keybuf.try_into().map_err(|_| ())?);
|
||||
let nonce = secretbox::Nonce([0; secretbox::NONCEBYTES]);
|
||||
|
||||
if encrypt {
|
||||
Ok(secretbox::seal(data, &nonce, &key))
|
||||
} else {
|
||||
secretbox::open(data, &nonce, &key)
|
||||
}
|
||||
}
|
||||
|
||||
mod test {
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
use super::*;
|
||||
|
||||
let version = "00";
|
||||
|
||||
println!("test str");
|
||||
let data = "Hello World";
|
||||
let encrypted = encrypt_str_or_original(data, version);
|
||||
let (decrypted, succ, store) = decrypt_str_or_original(&encrypted, version);
|
||||
println!("data: {data}");
|
||||
println!("encrypted: {encrypted}");
|
||||
println!("decrypted: {decrypted}");
|
||||
assert_eq!(data, decrypted);
|
||||
assert_eq!(version, &encrypted[..2]);
|
||||
assert!(succ);
|
||||
assert!(!store);
|
||||
let (_, _, store) = decrypt_str_or_original(&encrypted, "99");
|
||||
assert!(store);
|
||||
assert!(!decrypt_str_or_original(&decrypted, version).1);
|
||||
assert_eq!(encrypt_str_or_original(&encrypted, version), encrypted);
|
||||
|
||||
println!("test vec");
|
||||
let data: Vec<u8> = vec![1, 2, 3, 4, 5, 6];
|
||||
let encrypted = encrypt_vec_or_original(&data, version);
|
||||
let (decrypted, succ, store) = decrypt_vec_or_original(&encrypted, version);
|
||||
println!("data: {data:?}");
|
||||
println!("encrypted: {encrypted:?}");
|
||||
println!("decrypted: {decrypted:?}");
|
||||
assert_eq!(data, decrypted);
|
||||
assert_eq!(version.as_bytes(), &encrypted[..2]);
|
||||
assert!(!store);
|
||||
assert!(succ);
|
||||
let (_, _, store) = decrypt_vec_or_original(&encrypted, "99");
|
||||
assert!(store);
|
||||
assert!(!decrypt_vec_or_original(&decrypted, version).1);
|
||||
assert_eq!(encrypt_vec_or_original(&encrypted, version), encrypted);
|
||||
|
||||
println!("test original");
|
||||
let data = version.to_string() + "Hello World";
|
||||
let (decrypted, succ, store) = decrypt_str_or_original(&data, version);
|
||||
assert_eq!(data, decrypted);
|
||||
assert!(store);
|
||||
assert!(!succ);
|
||||
let verbytes = version.as_bytes();
|
||||
let data: Vec<u8> = vec![verbytes[0], verbytes[1], 1, 2, 3, 4, 5, 6];
|
||||
let (decrypted, succ, store) = decrypt_vec_or_original(&data, version);
|
||||
assert_eq!(data, decrypted);
|
||||
assert!(store);
|
||||
assert!(!succ);
|
||||
let (_, succ, store) = decrypt_str_or_original("", version);
|
||||
assert!(!store);
|
||||
assert!(!succ);
|
||||
let (_, succ, store) = decrypt_vec_or_original(&[], version);
|
||||
assert!(!store);
|
||||
assert!(!succ);
|
||||
}
|
||||
}
|
||||
157
libs/hbb_common/src/platform/linux.rs
Normal file
157
libs/hbb_common/src/platform/linux.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
use crate::ResultType;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref DISTRO: Distro = Distro::new();
|
||||
}
|
||||
|
||||
pub struct Distro {
|
||||
pub name: String,
|
||||
pub version_id: String,
|
||||
}
|
||||
|
||||
impl Distro {
|
||||
fn new() -> Self {
|
||||
let name = run_cmds("awk -F'=' '/^NAME=/ {print $2}' /etc/os-release".to_owned())
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.to_string();
|
||||
let version_id =
|
||||
run_cmds("awk -F'=' '/^VERSION_ID=/ {print $2}' /etc/os-release".to_owned())
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.to_string();
|
||||
Self { name, version_id }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_display_server() -> String {
|
||||
let mut session = get_values_of_seat0([0].to_vec())[0].clone();
|
||||
if session.is_empty() {
|
||||
// loginctl has not given the expected output. try something else.
|
||||
if let Ok(sid) = std::env::var("XDG_SESSION_ID") {
|
||||
// could also execute "cat /proc/self/sessionid"
|
||||
session = sid;
|
||||
}
|
||||
if session.is_empty() {
|
||||
session = run_cmds("cat /proc/self/sessionid".to_owned()).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
get_display_server_of_session(&session)
|
||||
}
|
||||
|
||||
fn get_display_server_of_session(session: &str) -> String {
|
||||
let mut display_server = if let Ok(output) =
|
||||
run_loginctl(Some(vec!["show-session", "-p", "Type", session]))
|
||||
// Check session type of the session
|
||||
{
|
||||
let display_server = String::from_utf8_lossy(&output.stdout)
|
||||
.replace("Type=", "")
|
||||
.trim_end()
|
||||
.into();
|
||||
if display_server == "tty" {
|
||||
// If the type is tty...
|
||||
if let Ok(output) = run_loginctl(Some(vec!["show-session", "-p", "TTY", session]))
|
||||
// Get the tty number
|
||||
{
|
||||
let tty: String = String::from_utf8_lossy(&output.stdout)
|
||||
.replace("TTY=", "")
|
||||
.trim_end()
|
||||
.into();
|
||||
if let Ok(xorg_results) = run_cmds(format!("ps -e | grep \"{tty}.\\\\+Xorg\""))
|
||||
// And check if Xorg is running on that tty
|
||||
{
|
||||
if xorg_results.trim_end() != "" {
|
||||
// If it is, manually return "x11", otherwise return tty
|
||||
return "x11".to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
display_server
|
||||
} else {
|
||||
"".to_owned()
|
||||
};
|
||||
if display_server.is_empty() || display_server == "tty" {
|
||||
// loginctl has not given the expected output. try something else.
|
||||
if let Ok(sestype) = std::env::var("XDG_SESSION_TYPE") {
|
||||
display_server = sestype;
|
||||
}
|
||||
}
|
||||
// If the session is not a tty, then just return the type as usual
|
||||
display_server
|
||||
}
|
||||
|
||||
pub fn get_values_of_seat0(indices: Vec<usize>) -> Vec<String> {
|
||||
if let Ok(output) = run_loginctl(None) {
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
if line.contains("seat0") {
|
||||
if let Some(sid) = line.split_whitespace().next() {
|
||||
if is_active(sid) {
|
||||
return indices
|
||||
.into_iter()
|
||||
.map(|idx| line.split_whitespace().nth(idx).unwrap_or("").to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// some case, there is no seat0 https://github.com/rustdesk/rustdesk/issues/73
|
||||
if let Ok(output) = run_loginctl(None) {
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
if let Some(sid) = line.split_whitespace().next() {
|
||||
let d = get_display_server_of_session(sid);
|
||||
if is_active(sid) && d != "tty" {
|
||||
return indices
|
||||
.into_iter()
|
||||
.map(|idx| line.split_whitespace().nth(idx).unwrap_or("").to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return indices
|
||||
.iter()
|
||||
.map(|_x| "".to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
}
|
||||
|
||||
fn is_active(sid: &str) -> bool {
|
||||
if let Ok(output) = run_loginctl(Some(vec!["show-session", "-p", "State", sid])) {
|
||||
String::from_utf8_lossy(&output.stdout).contains("active")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_cmds(cmds: String) -> ResultType<String> {
|
||||
let output = std::process::Command::new("sh")
|
||||
.args(vec!["-c", &cmds])
|
||||
.output()?;
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "flatpak"))]
|
||||
fn run_loginctl(args: Option<Vec<&str>>) -> std::io::Result<std::process::Output> {
|
||||
let mut cmd = std::process::Command::new("loginctl");
|
||||
if let Some(a) = args {
|
||||
return cmd.args(a).output();
|
||||
}
|
||||
cmd.output()
|
||||
}
|
||||
|
||||
#[cfg(feature = "flatpak")]
|
||||
fn run_loginctl(args: Option<Vec<&str>>) -> std::io::Result<std::process::Output> {
|
||||
let mut l_args = String::from("loginctl");
|
||||
if let Some(a) = args {
|
||||
l_args = format!("{} {}", l_args, a.join(" "));
|
||||
}
|
||||
std::process::Command::new("flatpak-spawn")
|
||||
.args(vec![String::from("--host"), l_args])
|
||||
.output()
|
||||
}
|
||||
2
libs/hbb_common/src/platform/mod.rs
Normal file
2
libs/hbb_common/src/platform/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod linux;
|
||||
1
libs/hbb_common/src/protos/mod.rs
Normal file
1
libs/hbb_common/src/protos/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
include!(concat!(env!("OUT_DIR"), "/protos/mod.rs"));
|
||||
135
libs/hbb_common/src/quic.rs
Normal file
135
libs/hbb_common/src/quic.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
use crate::{allow_err, anyhow::anyhow, ResultType};
|
||||
use protobuf::Message;
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
use tokio::{self, stream::StreamExt, sync::mpsc};
|
||||
|
||||
const QUIC_HBB: &[&[u8]] = &[b"hbb"];
|
||||
const SERVER_NAME: &str = "hbb";
|
||||
|
||||
type Sender = mpsc::UnboundedSender<Value>;
|
||||
type Receiver = mpsc::UnboundedReceiver<Value>;
|
||||
|
||||
pub fn new_server(socket: std::net::UdpSocket) -> ResultType<(Server, SocketAddr)> {
|
||||
let mut transport_config = quinn::TransportConfig::default();
|
||||
transport_config.stream_window_uni(0);
|
||||
let mut server_config = quinn::ServerConfig::default();
|
||||
server_config.transport = Arc::new(transport_config);
|
||||
let mut server_config = quinn::ServerConfigBuilder::new(server_config);
|
||||
server_config.protocols(QUIC_HBB);
|
||||
// server_config.enable_keylog();
|
||||
// server_config.use_stateless_retry(true);
|
||||
let mut endpoint = quinn::Endpoint::builder();
|
||||
endpoint.listen(server_config.build());
|
||||
let (end, incoming) = endpoint.with_socket(socket)?;
|
||||
Ok((Server { incoming }, end.local_addr()?))
|
||||
}
|
||||
|
||||
pub async fn new_client(local_addr: &SocketAddr, peer: &SocketAddr) -> ResultType<Connection> {
|
||||
let mut endpoint = quinn::Endpoint::builder();
|
||||
let mut client_config = quinn::ClientConfigBuilder::default();
|
||||
client_config.protocols(QUIC_HBB);
|
||||
//client_config.enable_keylog();
|
||||
endpoint.default_client_config(client_config.build());
|
||||
let (endpoint, _) = endpoint.bind(local_addr)?;
|
||||
let new_conn = endpoint.connect(peer, SERVER_NAME)?.await?;
|
||||
Connection::new_for_client(new_conn.connection).await
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
incoming: quinn::Incoming,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
#[inline]
|
||||
pub async fn next(&mut self) -> ResultType<Option<Connection>> {
|
||||
Connection::new_for_server(&mut self.incoming).await
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Connection {
|
||||
conn: quinn::Connection,
|
||||
tx: quinn::SendStream,
|
||||
rx: Receiver,
|
||||
}
|
||||
|
||||
type Value = ResultType<Vec<u8>>;
|
||||
|
||||
impl Connection {
|
||||
async fn new_for_server(incoming: &mut quinn::Incoming) -> ResultType<Option<Self>> {
|
||||
if let Some(conn) = incoming.next().await {
|
||||
let quinn::NewConnection {
|
||||
connection: conn,
|
||||
// uni_streams,
|
||||
mut bi_streams,
|
||||
..
|
||||
} = conn.await?;
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Value>();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let stream = bi_streams.next().await;
|
||||
if let Some(stream) = stream {
|
||||
let stream = match stream {
|
||||
Err(e) => {
|
||||
tx.send(Err(e.into())).ok();
|
||||
break;
|
||||
}
|
||||
Ok(s) => s,
|
||||
};
|
||||
let cloned = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
allow_err!(handle_request(stream.1, cloned).await);
|
||||
});
|
||||
} else {
|
||||
tx.send(Err(anyhow!("Reset by the peer"))).ok();
|
||||
break;
|
||||
}
|
||||
}
|
||||
log::info!("Exit connection outer loop");
|
||||
});
|
||||
let tx = conn.open_uni().await?;
|
||||
Ok(Some(Self { conn, tx, rx }))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
async fn new_for_client(conn: quinn::Connection) -> ResultType<Self> {
|
||||
let (tx, rx_quic) = conn.open_bi().await?;
|
||||
let (tx_mpsc, rx) = mpsc::unbounded_channel::<Value>();
|
||||
tokio::spawn(async move {
|
||||
allow_err!(handle_request(rx_quic, tx_mpsc).await);
|
||||
});
|
||||
Ok(Self { conn, tx, rx })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn next(&mut self) -> Option<Value> {
|
||||
// None is returned when all Sender halves have dropped,
|
||||
// indicating that no further values can be sent on the channel.
|
||||
self.rx.recv().await
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn remote_address(&self) -> SocketAddr {
|
||||
self.conn.remote_address()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send_raw(&mut self, bytes: &[u8]) -> ResultType<()> {
|
||||
self.tx.write_all(bytes).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send(&mut self, msg: &dyn Message) -> ResultType<()> {
|
||||
match msg.write_to_bytes() {
|
||||
Ok(bytes) => self.send_raw(&bytes).await?,
|
||||
err => allow_err!(err),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_request(rx: quinn::RecvStream, tx: Sender) -> ResultType<()> {
|
||||
Ok(())
|
||||
}
|
||||
281
libs/hbb_common/src/socket_client.rs
Normal file
281
libs/hbb_common/src/socket_client.rs
Normal file
@@ -0,0 +1,281 @@
|
||||
use crate::{
|
||||
config::{Config, NetworkType},
|
||||
tcp::FramedStream,
|
||||
udp::FramedSocket,
|
||||
ResultType,
|
||||
};
|
||||
use anyhow::Context;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::ToSocketAddrs;
|
||||
use tokio_socks::{IntoTargetAddr, TargetAddr};
|
||||
|
||||
#[inline]
|
||||
pub fn check_port<T: std::string::ToString>(host: T, port: i32) -> String {
|
||||
let host = host.to_string();
|
||||
if crate::is_ipv6_str(&host) {
|
||||
if host.starts_with('[') {
|
||||
return host;
|
||||
}
|
||||
return format!("[{host}]:{port}");
|
||||
}
|
||||
if !host.contains(':') {
|
||||
return format!("{host}:{port}");
|
||||
}
|
||||
host
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn increase_port<T: std::string::ToString>(host: T, offset: i32) -> String {
|
||||
let host = host.to_string();
|
||||
if crate::is_ipv6_str(&host) {
|
||||
if host.starts_with('[') {
|
||||
let tmp: Vec<&str> = host.split("]:").collect();
|
||||
if tmp.len() == 2 {
|
||||
let port: i32 = tmp[1].parse().unwrap_or(0);
|
||||
if port > 0 {
|
||||
return format!("{}]:{}", tmp[0], port + offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if host.contains(':') {
|
||||
let tmp: Vec<&str> = host.split(':').collect();
|
||||
if tmp.len() == 2 {
|
||||
let port: i32 = tmp[1].parse().unwrap_or(0);
|
||||
if port > 0 {
|
||||
return format!("{}:{}", tmp[0], port + offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
host
|
||||
}
|
||||
|
||||
pub fn test_if_valid_server(host: &str) -> String {
|
||||
let host = check_port(host, 0);
|
||||
|
||||
use std::net::ToSocketAddrs;
|
||||
match Config::get_network_type() {
|
||||
NetworkType::Direct => match host.to_socket_addrs() {
|
||||
Err(err) => err.to_string(),
|
||||
Ok(_) => "".to_owned(),
|
||||
},
|
||||
NetworkType::ProxySocks => match &host.into_target_addr() {
|
||||
Err(err) => err.to_string(),
|
||||
Ok(_) => "".to_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IsResolvedSocketAddr {
|
||||
fn resolve(&self) -> Option<&SocketAddr>;
|
||||
}
|
||||
|
||||
impl IsResolvedSocketAddr for SocketAddr {
|
||||
fn resolve(&self) -> Option<&SocketAddr> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IsResolvedSocketAddr for String {
|
||||
fn resolve(&self) -> Option<&SocketAddr> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl IsResolvedSocketAddr for &str {
|
||||
fn resolve(&self) -> Option<&SocketAddr> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn connect_tcp<
|
||||
't,
|
||||
T: IntoTargetAddr<'t> + ToSocketAddrs + IsResolvedSocketAddr + std::fmt::Display,
|
||||
>(
|
||||
target: T,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<FramedStream> {
|
||||
connect_tcp_local(target, None, ms_timeout).await
|
||||
}
|
||||
|
||||
pub async fn connect_tcp_local<
|
||||
't,
|
||||
T: IntoTargetAddr<'t> + ToSocketAddrs + IsResolvedSocketAddr + std::fmt::Display,
|
||||
>(
|
||||
target: T,
|
||||
local: Option<SocketAddr>,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<FramedStream> {
|
||||
if let Some(conf) = Config::get_socks() {
|
||||
return FramedStream::connect(
|
||||
conf.proxy.as_str(),
|
||||
target,
|
||||
local,
|
||||
conf.username.as_str(),
|
||||
conf.password.as_str(),
|
||||
ms_timeout,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if let Some(target) = target.resolve() {
|
||||
if let Some(local) = local {
|
||||
if local.is_ipv6() && target.is_ipv4() {
|
||||
let target = query_nip_io(target).await?;
|
||||
return FramedStream::new(target, Some(local), ms_timeout).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
FramedStream::new(target, local, ms_timeout).await
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_ipv4(target: &TargetAddr<'_>) -> bool {
|
||||
match target {
|
||||
TargetAddr::Ip(addr) => addr.is_ipv4(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn query_nip_io(addr: &SocketAddr) -> ResultType<SocketAddr> {
|
||||
tokio::net::lookup_host(format!("{}.nip.io:{}", addr.ip(), addr.port()))
|
||||
.await?
|
||||
.find(|x| x.is_ipv6())
|
||||
.context("Failed to get ipv6 from nip.io")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ipv4_to_ipv6(addr: String, ipv4: bool) -> String {
|
||||
if !ipv4 && crate::is_ipv4_str(&addr) {
|
||||
if let Some(ip) = addr.split(':').next() {
|
||||
return addr.replace(ip, &format!("{ip}.nip.io"));
|
||||
}
|
||||
}
|
||||
addr
|
||||
}
|
||||
|
||||
async fn test_target(target: &str) -> ResultType<SocketAddr> {
|
||||
if let Ok(Ok(s)) = super::timeout(1000, tokio::net::TcpStream::connect(target)).await {
|
||||
if let Ok(addr) = s.peer_addr() {
|
||||
return Ok(addr);
|
||||
}
|
||||
}
|
||||
tokio::net::lookup_host(target)
|
||||
.await?
|
||||
.next()
|
||||
.context(format!("Failed to look up host for {target}"))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn new_udp_for(
|
||||
target: &str,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<(FramedSocket, TargetAddr<'static>)> {
|
||||
let (ipv4, target) = if NetworkType::Direct == Config::get_network_type() {
|
||||
let addr = test_target(target).await?;
|
||||
(addr.is_ipv4(), addr.into_target_addr()?)
|
||||
} else {
|
||||
(true, target.into_target_addr()?)
|
||||
};
|
||||
Ok((
|
||||
new_udp(Config::get_any_listen_addr(ipv4), ms_timeout).await?,
|
||||
target.to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn new_udp<T: ToSocketAddrs>(local: T, ms_timeout: u64) -> ResultType<FramedSocket> {
|
||||
match Config::get_socks() {
|
||||
None => Ok(FramedSocket::new(local).await?),
|
||||
Some(conf) => {
|
||||
let socket = FramedSocket::new_proxy(
|
||||
conf.proxy.as_str(),
|
||||
local,
|
||||
conf.username.as_str(),
|
||||
conf.password.as_str(),
|
||||
ms_timeout,
|
||||
)
|
||||
.await?;
|
||||
Ok(socket)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn rebind_udp_for(
|
||||
target: &str,
|
||||
) -> ResultType<Option<(FramedSocket, TargetAddr<'static>)>> {
|
||||
if Config::get_network_type() != NetworkType::Direct {
|
||||
return Ok(None);
|
||||
}
|
||||
let addr = test_target(target).await?;
|
||||
let v4 = addr.is_ipv4();
|
||||
Ok(Some((
|
||||
FramedSocket::new(Config::get_any_listen_addr(v4)).await?,
|
||||
addr.into_target_addr()?.to_owned(),
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::ToSocketAddrs;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_nat64() {
|
||||
test_nat64_async();
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn test_nat64_async() {
|
||||
assert_eq!(ipv4_to_ipv6("1.1.1.1".to_owned(), true), "1.1.1.1");
|
||||
assert_eq!(ipv4_to_ipv6("1.1.1.1".to_owned(), false), "1.1.1.1.nip.io");
|
||||
assert_eq!(
|
||||
ipv4_to_ipv6("1.1.1.1:8080".to_owned(), false),
|
||||
"1.1.1.1.nip.io:8080"
|
||||
);
|
||||
assert_eq!(
|
||||
ipv4_to_ipv6("rustdesk.com".to_owned(), false),
|
||||
"rustdesk.com"
|
||||
);
|
||||
if ("rustdesk.com:80")
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap()
|
||||
.is_ipv6()
|
||||
{
|
||||
assert!(query_nip_io(&"1.1.1.1:80".parse().unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_ipv6());
|
||||
return;
|
||||
}
|
||||
assert!(query_nip_io(&"1.1.1.1:80".parse().unwrap()).await.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_test_if_valid_server() {
|
||||
assert!(!test_if_valid_server("a").is_empty());
|
||||
// on Linux, "1" is resolved to "0.0.0.1"
|
||||
assert!(test_if_valid_server("1.1.1.1").is_empty());
|
||||
assert!(test_if_valid_server("1.1.1.1:1").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_port() {
|
||||
assert_eq!(check_port("[1:2]:12", 32), "[1:2]:12");
|
||||
assert_eq!(check_port("1:2", 32), "[1:2]:32");
|
||||
assert_eq!(check_port("z1:2", 32), "z1:2");
|
||||
assert_eq!(check_port("1.1.1.1", 32), "1.1.1.1:32");
|
||||
assert_eq!(check_port("1.1.1.1:32", 32), "1.1.1.1:32");
|
||||
assert_eq!(check_port("test.com:32", 0), "test.com:32");
|
||||
assert_eq!(increase_port("[1:2]:12", 1), "[1:2]:13");
|
||||
assert_eq!(increase_port("1.2.2.4:12", 1), "1.2.2.4:13");
|
||||
assert_eq!(increase_port("1.2.2.4", 1), "1.2.2.4");
|
||||
assert_eq!(increase_port("test.com", 1), "test.com");
|
||||
assert_eq!(increase_port("test.com:13", 4), "test.com:17");
|
||||
assert_eq!(increase_port("1:13", 4), "1:13");
|
||||
assert_eq!(increase_port("22:1:13", 4), "22:1:13");
|
||||
assert_eq!(increase_port("z1:2", 1), "z1:3");
|
||||
}
|
||||
}
|
||||
325
libs/hbb_common/src/tcp.rs
Normal file
325
libs/hbb_common/src/tcp.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
use crate::{bail, bytes_codec::BytesCodec, ResultType};
|
||||
use anyhow::Context as AnyhowCtx;
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use protobuf::Message;
|
||||
use sodiumoxide::crypto::secretbox::{self, Key, Nonce};
|
||||
use std::{
|
||||
io::{self, Error, ErrorKind},
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
ops::{Deref, DerefMut},
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite, ReadBuf},
|
||||
net::{lookup_host, TcpListener, TcpSocket, ToSocketAddrs},
|
||||
};
|
||||
use tokio_socks::{tcp::Socks5Stream, IntoTargetAddr, ToProxyAddrs};
|
||||
use tokio_util::codec::Framed;
|
||||
|
||||
pub trait TcpStreamTrait: AsyncRead + AsyncWrite + Unpin {}
|
||||
pub struct DynTcpStream(Box<dyn TcpStreamTrait + Send + Sync>);
|
||||
|
||||
pub struct FramedStream(
|
||||
Framed<DynTcpStream, BytesCodec>,
|
||||
SocketAddr,
|
||||
Option<(Key, u64, u64)>,
|
||||
u64,
|
||||
);
|
||||
|
||||
impl Deref for FramedStream {
|
||||
type Target = Framed<DynTcpStream, BytesCodec>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for FramedStream {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DynTcpStream {
|
||||
type Target = Box<dyn TcpStreamTrait + Send + Sync>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for DynTcpStream {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn new_socket(addr: std::net::SocketAddr, reuse: bool) -> Result<TcpSocket, std::io::Error> {
|
||||
let socket = match addr {
|
||||
std::net::SocketAddr::V4(..) => TcpSocket::new_v4()?,
|
||||
std::net::SocketAddr::V6(..) => TcpSocket::new_v6()?,
|
||||
};
|
||||
if reuse {
|
||||
// windows has no reuse_port, but it's reuse_address
|
||||
// almost equals to unix's reuse_port + reuse_address,
|
||||
// though may introduce nondeterministic behavior
|
||||
#[cfg(unix)]
|
||||
socket.set_reuseport(true)?;
|
||||
socket.set_reuseaddr(true)?;
|
||||
}
|
||||
socket.bind(addr)?;
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
impl FramedStream {
|
||||
pub async fn new<T: ToSocketAddrs + std::fmt::Display>(
|
||||
remote_addr: T,
|
||||
local_addr: Option<SocketAddr>,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<Self> {
|
||||
for remote_addr in lookup_host(&remote_addr).await? {
|
||||
let local = if let Some(addr) = local_addr {
|
||||
addr
|
||||
} else {
|
||||
crate::config::Config::get_any_listen_addr(remote_addr.is_ipv4())
|
||||
};
|
||||
if let Ok(socket) = new_socket(local, true) {
|
||||
if let Ok(Ok(stream)) =
|
||||
super::timeout(ms_timeout, socket.connect(remote_addr)).await
|
||||
{
|
||||
stream.set_nodelay(true).ok();
|
||||
let addr = stream.local_addr()?;
|
||||
return Ok(Self(
|
||||
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
|
||||
addr,
|
||||
None,
|
||||
0,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!(format!("Failed to connect to {remote_addr}"));
|
||||
}
|
||||
|
||||
pub async fn connect<'a, 't, P, T>(
|
||||
proxy: P,
|
||||
target: T,
|
||||
local_addr: Option<SocketAddr>,
|
||||
username: &'a str,
|
||||
password: &'a str,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<Self>
|
||||
where
|
||||
P: ToProxyAddrs,
|
||||
T: IntoTargetAddr<'t>,
|
||||
{
|
||||
if let Some(Ok(proxy)) = proxy.to_proxy_addrs().next().await {
|
||||
let local = if let Some(addr) = local_addr {
|
||||
addr
|
||||
} else {
|
||||
crate::config::Config::get_any_listen_addr(proxy.is_ipv4())
|
||||
};
|
||||
let stream =
|
||||
super::timeout(ms_timeout, new_socket(local, true)?.connect(proxy)).await??;
|
||||
stream.set_nodelay(true).ok();
|
||||
let stream = if username.trim().is_empty() {
|
||||
super::timeout(
|
||||
ms_timeout,
|
||||
Socks5Stream::connect_with_socket(stream, target),
|
||||
)
|
||||
.await??
|
||||
} else {
|
||||
super::timeout(
|
||||
ms_timeout,
|
||||
Socks5Stream::connect_with_password_and_socket(
|
||||
stream, target, username, password,
|
||||
),
|
||||
)
|
||||
.await??
|
||||
};
|
||||
let addr = stream.local_addr()?;
|
||||
return Ok(Self(
|
||||
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
|
||||
addr,
|
||||
None,
|
||||
0,
|
||||
));
|
||||
}
|
||||
bail!("could not resolve to any address");
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.1
|
||||
}
|
||||
|
||||
pub fn set_send_timeout(&mut self, ms: u64) {
|
||||
self.3 = ms;
|
||||
}
|
||||
|
||||
pub fn from(stream: impl TcpStreamTrait + Send + Sync + 'static, addr: SocketAddr) -> Self {
|
||||
Self(
|
||||
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
|
||||
addr,
|
||||
None,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn set_raw(&mut self) {
|
||||
self.0.codec_mut().set_raw();
|
||||
self.2 = None;
|
||||
}
|
||||
|
||||
pub fn is_secured(&self) -> bool {
|
||||
self.2.is_some()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send(&mut self, msg: &impl Message) -> ResultType<()> {
|
||||
self.send_raw(msg.write_to_bytes()?).await
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send_raw(&mut self, msg: Vec<u8>) -> ResultType<()> {
|
||||
let mut msg = msg;
|
||||
if let Some(key) = self.2.as_mut() {
|
||||
key.1 += 1;
|
||||
let nonce = Self::get_nonce(key.1);
|
||||
msg = secretbox::seal(&msg, &nonce, &key.0);
|
||||
}
|
||||
self.send_bytes(bytes::Bytes::from(msg)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send_bytes(&mut self, bytes: Bytes) -> ResultType<()> {
|
||||
if self.3 > 0 {
|
||||
super::timeout(self.3, self.0.send(bytes)).await??;
|
||||
} else {
|
||||
self.0.send(bytes).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn next(&mut self) -> Option<Result<BytesMut, Error>> {
|
||||
let mut res = self.0.next().await;
|
||||
if let Some(key) = self.2.as_mut() {
|
||||
if let Some(Ok(bytes)) = res.as_mut() {
|
||||
key.2 += 1;
|
||||
let nonce = Self::get_nonce(key.2);
|
||||
match secretbox::open(bytes, &nonce, &key.0) {
|
||||
Ok(res) => {
|
||||
bytes.clear();
|
||||
bytes.put_slice(&res);
|
||||
}
|
||||
Err(()) => {
|
||||
return Some(Err(Error::new(ErrorKind::Other, "decryption error")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn next_timeout(&mut self, ms: u64) -> Option<Result<BytesMut, Error>> {
|
||||
if let Ok(res) = super::timeout(ms, self.next()).await {
|
||||
res
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_key(&mut self, key: Key) {
|
||||
self.2 = Some((key, 0, 0));
|
||||
}
|
||||
|
||||
fn get_nonce(seqnum: u64) -> Nonce {
|
||||
let mut nonce = Nonce([0u8; secretbox::NONCEBYTES]);
|
||||
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_le_bytes());
|
||||
nonce
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_BACKLOG: u32 = 128;
|
||||
|
||||
pub async fn new_listener<T: ToSocketAddrs>(addr: T, reuse: bool) -> ResultType<TcpListener> {
|
||||
if !reuse {
|
||||
Ok(TcpListener::bind(addr).await?)
|
||||
} else {
|
||||
let addr = lookup_host(&addr)
|
||||
.await?
|
||||
.next()
|
||||
.context("could not resolve to any address")?;
|
||||
new_socket(addr, true)?
|
||||
.listen(DEFAULT_BACKLOG)
|
||||
.map_err(anyhow::Error::msg)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn listen_any(port: u16) -> ResultType<TcpListener> {
|
||||
if let Ok(mut socket) = TcpSocket::new_v6() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::io::{FromRawFd, IntoRawFd};
|
||||
let raw_fd = socket.into_raw_fd();
|
||||
let sock2 = unsafe { socket2::Socket::from_raw_fd(raw_fd) };
|
||||
sock2.set_only_v6(false).ok();
|
||||
socket = unsafe { TcpSocket::from_raw_fd(sock2.into_raw_fd()) };
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::prelude::{FromRawSocket, IntoRawSocket};
|
||||
let raw_socket = socket.into_raw_socket();
|
||||
let sock2 = unsafe { socket2::Socket::from_raw_socket(raw_socket) };
|
||||
sock2.set_only_v6(false).ok();
|
||||
socket = unsafe { TcpSocket::from_raw_socket(sock2.into_raw_socket()) };
|
||||
}
|
||||
if socket
|
||||
.bind(SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port))
|
||||
.is_ok()
|
||||
{
|
||||
if let Ok(l) = socket.listen(DEFAULT_BACKLOG) {
|
||||
return Ok(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
let s = TcpSocket::new_v4()?;
|
||||
s.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port))?;
|
||||
Ok(s.listen(DEFAULT_BACKLOG)?)
|
||||
}
|
||||
|
||||
impl Unpin for DynTcpStream {}
|
||||
|
||||
impl AsyncRead for DynTcpStream {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
AsyncRead::poll_read(Pin::new(&mut self.0), cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for DynTcpStream {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
AsyncWrite::poll_write(Pin::new(&mut self.0), cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
AsyncWrite::poll_flush(Pin::new(&mut self.0), cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
AsyncWrite::poll_shutdown(Pin::new(&mut self.0), cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + AsyncWrite + Unpin> TcpStreamTrait for R {}
|
||||
170
libs/hbb_common/src/udp.rs
Normal file
170
libs/hbb_common/src/udp.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use crate::ResultType;
|
||||
use anyhow::{anyhow, Context};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use protobuf::Message;
|
||||
use socket2::{Domain, Socket, Type};
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::{lookup_host, ToSocketAddrs, UdpSocket};
|
||||
use tokio_socks::{udp::Socks5UdpFramed, IntoTargetAddr, TargetAddr, ToProxyAddrs};
|
||||
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
|
||||
|
||||
pub enum FramedSocket {
|
||||
Direct(UdpFramed<BytesCodec>),
|
||||
ProxySocks(Socks5UdpFramed),
|
||||
}
|
||||
|
||||
fn new_socket(addr: SocketAddr, reuse: bool, buf_size: usize) -> Result<Socket, std::io::Error> {
|
||||
let socket = match addr {
|
||||
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), Type::dgram(), None),
|
||||
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), Type::dgram(), None),
|
||||
}?;
|
||||
if reuse {
|
||||
// windows has no reuse_port, but it's reuse_address
|
||||
// almost equals to unix's reuse_port + reuse_address,
|
||||
// though may introduce nondeterministic behavior
|
||||
#[cfg(unix)]
|
||||
socket.set_reuse_port(true)?;
|
||||
socket.set_reuse_address(true)?;
|
||||
}
|
||||
// only nonblocking work with tokio, https://stackoverflow.com/questions/64649405/receiver-on-tokiompscchannel-only-receives-messages-when-buffer-is-full
|
||||
socket.set_nonblocking(true)?;
|
||||
if buf_size > 0 {
|
||||
socket.set_recv_buffer_size(buf_size).ok();
|
||||
}
|
||||
log::info!(
|
||||
"Receive buf size of udp {}: {:?}",
|
||||
addr,
|
||||
socket.recv_buffer_size()
|
||||
);
|
||||
if addr.is_ipv6() && addr.ip().is_unspecified() && addr.port() > 0 {
|
||||
socket.set_only_v6(false).ok();
|
||||
}
|
||||
socket.bind(&addr.into())?;
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
impl FramedSocket {
|
||||
pub async fn new<T: ToSocketAddrs>(addr: T) -> ResultType<Self> {
|
||||
Self::new_reuse(addr, false, 0).await
|
||||
}
|
||||
|
||||
pub async fn new_reuse<T: ToSocketAddrs>(
|
||||
addr: T,
|
||||
reuse: bool,
|
||||
buf_size: usize,
|
||||
) -> ResultType<Self> {
|
||||
let addr = lookup_host(&addr)
|
||||
.await?
|
||||
.next()
|
||||
.context("could not resolve to any address")?;
|
||||
Ok(Self::Direct(UdpFramed::new(
|
||||
UdpSocket::from_std(new_socket(addr, reuse, buf_size)?.into_udp_socket())?,
|
||||
BytesCodec::new(),
|
||||
)))
|
||||
}
|
||||
|
||||
pub async fn new_proxy<'a, 't, P: ToProxyAddrs, T: ToSocketAddrs>(
|
||||
proxy: P,
|
||||
local: T,
|
||||
username: &'a str,
|
||||
password: &'a str,
|
||||
ms_timeout: u64,
|
||||
) -> ResultType<Self> {
|
||||
let framed = if username.trim().is_empty() {
|
||||
super::timeout(ms_timeout, Socks5UdpFramed::connect(proxy, Some(local))).await??
|
||||
} else {
|
||||
super::timeout(
|
||||
ms_timeout,
|
||||
Socks5UdpFramed::connect_with_password(proxy, Some(local), username, password),
|
||||
)
|
||||
.await??
|
||||
};
|
||||
log::trace!(
|
||||
"Socks5 udp connected, local addr: {:?}, target addr: {}",
|
||||
framed.local_addr(),
|
||||
framed.socks_addr()
|
||||
);
|
||||
Ok(Self::ProxySocks(framed))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn send(
|
||||
&mut self,
|
||||
msg: &impl Message,
|
||||
addr: impl IntoTargetAddr<'_>,
|
||||
) -> ResultType<()> {
|
||||
let addr = addr.into_target_addr()?.to_owned();
|
||||
let send_data = Bytes::from(msg.write_to_bytes()?);
|
||||
match self {
|
||||
Self::Direct(f) => {
|
||||
if let TargetAddr::Ip(addr) = addr {
|
||||
f.send((send_data, addr)).await?
|
||||
}
|
||||
}
|
||||
Self::ProxySocks(f) => f.send((send_data, addr)).await?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// https://stackoverflow.com/a/68733302/1926020
|
||||
#[inline]
|
||||
pub async fn send_raw(
|
||||
&mut self,
|
||||
msg: &'static [u8],
|
||||
addr: impl IntoTargetAddr<'static>,
|
||||
) -> ResultType<()> {
|
||||
let addr = addr.into_target_addr()?.to_owned();
|
||||
|
||||
match self {
|
||||
Self::Direct(f) => {
|
||||
if let TargetAddr::Ip(addr) = addr {
|
||||
f.send((Bytes::from(msg), addr)).await?
|
||||
}
|
||||
}
|
||||
Self::ProxySocks(f) => f.send((Bytes::from(msg), addr)).await?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn next(&mut self) -> Option<ResultType<(BytesMut, TargetAddr<'static>)>> {
|
||||
match self {
|
||||
Self::Direct(f) => match f.next().await {
|
||||
Some(Ok((data, addr))) => {
|
||||
Some(Ok((data, addr.into_target_addr().ok()?.to_owned())))
|
||||
}
|
||||
Some(Err(e)) => Some(Err(anyhow!(e))),
|
||||
None => None,
|
||||
},
|
||||
Self::ProxySocks(f) => match f.next().await {
|
||||
Some(Ok((data, _))) => Some(Ok((data.data, data.dst_addr))),
|
||||
Some(Err(e)) => Some(Err(anyhow!(e))),
|
||||
None => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn next_timeout(
|
||||
&mut self,
|
||||
ms: u64,
|
||||
) -> Option<ResultType<(BytesMut, TargetAddr<'static>)>> {
|
||||
if let Ok(res) =
|
||||
tokio::time::timeout(std::time::Duration::from_millis(ms), self.next()).await
|
||||
{
|
||||
res
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> Option<SocketAddr> {
|
||||
if let FramedSocket::Direct(x) = self {
|
||||
if let Ok(v) = x.get_ref().local_addr() {
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
45
mod.rs
45
mod.rs
@@ -1,45 +0,0 @@
|
||||
mod src;
|
||||
pub use src::*;
|
||||
|
||||
use hbb_common::{allow_err, log};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref STOP: Arc<Mutex<bool>> = Arc::new(Mutex::new(true));
|
||||
}
|
||||
|
||||
pub fn bootstrap(key: &str, host: &str) {
|
||||
let port = rendezvous_server::DEFAULT_PORT;
|
||||
let addr = format!("0.0.0.0:{}", port);
|
||||
let addr2 = format!("0.0.0.0:{}", port.parse::<i32>().unwrap_or(0) - 1);
|
||||
let relay_servers: Vec<String> = vec![format!("{}:{}", host, relay_server::DEFAULT_PORT)];
|
||||
let tmp_key = key.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
allow_err!(rendezvous_server::RendezvousServer::start(
|
||||
&addr,
|
||||
&addr2,
|
||||
relay_servers,
|
||||
0,
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
&tmp_key,
|
||||
STOP.clone(),
|
||||
));
|
||||
});
|
||||
let tmp_key = key.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
allow_err!(relay_server::start(
|
||||
relay_server::DEFAULT_PORT,
|
||||
&tmp_key,
|
||||
STOP.clone()
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop() {
|
||||
*STOP.lock().unwrap() = true;
|
||||
}
|
||||
|
||||
pub fn start() {
|
||||
*STOP.lock().unwrap() = false;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
cargo build --release
|
||||
strip target/release/hbbr
|
||||
strip target/release/hbbs
|
||||
sudo docker image build -t rustdesk/rustdesk-server .
|
||||
#sudo docker login
|
||||
sudo docker image push rustdesk/rustdesk-server:latest
|
||||
22
spk.sh
22
spk.sh
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# here is Breaking Changes of package in 7.0: https://global.download.synology.com/download/Document/Software/DeveloperGuide/Firmware/DSM/7.0/enu/DSM_Developer_Guide_7_0_Beta.pdf
|
||||
# https://blog.cmj.tw/SynologyApp.htm 暂时不搞签名
|
||||
/bin/rm -rf package
|
||||
mkdir package
|
||||
cd package
|
||||
mkdir bin logs config
|
||||
echo port=21116 > config/hbbs.conf
|
||||
echo key= >> config/hbbs.conf
|
||||
echo email= >> config/hbbs.conf
|
||||
echo port=21117 > config/hbbr.conf
|
||||
cp ../target/release/hbbs bin/
|
||||
cp ../target/release/hbbr bin/
|
||||
strip bin/hbbs
|
||||
strip bin/hbbr
|
||||
tar -czf ../spk/package.tgz *
|
||||
cd ..
|
||||
cd spk
|
||||
#md5 package.tgz | awk '{print "checksum=\"" $4 "\""}' >> INFO
|
||||
file=rustdesk-server-synology-x64.spk
|
||||
tar -cvf $file *
|
||||
mv $file ..
|
||||
18
spk/INFO
18
spk/INFO
@@ -1,18 +0,0 @@
|
||||
package="RustDesk Server"
|
||||
version="1.1.3"
|
||||
description="RustDesk is a remote desktop software allowing your own rendezvous/relay server. It attempts to make direct connect via TCP hole punch first, and then forward via relay server if direct connection fails. 4 ports are used. NAT test port: 21115(tcp), ID/rendezvous port: 21116(tcp/udp), relay port: 21117(tcp), Email: (), Key: ()"
|
||||
displayname="RustDesk Rendezvous/Relay Server"
|
||||
maintainer="CarrieZ Studio"
|
||||
maintainer_url="https://rustdesk.com/zh/"
|
||||
distributor="RustDesk & 裙下孤魂"
|
||||
support_url="https://rustdesk.com/contact/"
|
||||
arch="apollolake avoton braswell broadwell broadwellnk bromolow cedarview denverton dockerx64 geminilake grantley kvmx64 purley v1000 x86 x86_64"
|
||||
os_min_ver="6.1"
|
||||
reloadui="yes"
|
||||
startable="yes"
|
||||
thirdparty="yes"
|
||||
install_reboot="no"
|
||||
install_dep_packages=""
|
||||
install_conflict_packages=""
|
||||
extractsize=""
|
||||
checkport="no"
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 7.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
@@ -1,54 +0,0 @@
|
||||
[{
|
||||
"step_title": "Install Settings",
|
||||
"items": [{
|
||||
"type": "textfield",
|
||||
"desc": "Listening Ports",
|
||||
"subitems": [{
|
||||
"key": "hbbs_port",
|
||||
"desc": "RustDesk ID Server Port",
|
||||
"defaultValue": "21116",
|
||||
"validator": {
|
||||
"allowBlank": false,
|
||||
"regex": {
|
||||
"expr": "/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/",
|
||||
"errorText": "Digit number only"
|
||||
}
|
||||
}
|
||||
}, {
|
||||
"key": "hbbr_port",
|
||||
"desc": "RustDesk Relay Server Port",
|
||||
"defaultValue": "21117",
|
||||
"validator": {
|
||||
"allowBlank": false,
|
||||
"regex": {
|
||||
"expr": "/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/",
|
||||
"errorText": "Digit number only"
|
||||
}
|
||||
}
|
||||
}]
|
||||
},{
|
||||
"type": "textfield",
|
||||
"desc": "Registered email, check http://rustdesk.com/server for more information",
|
||||
"subitems": [{
|
||||
"key": "email",
|
||||
"desc": "Email",
|
||||
"validator": {
|
||||
"allowBlank": false,
|
||||
"regex": {
|
||||
"expr": "/^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$/",
|
||||
"errorText": "Invalid email format"
|
||||
}
|
||||
}
|
||||
}]
|
||||
},{
|
||||
"type": "textfield",
|
||||
"desc": "Only allow the client with the same key",
|
||||
"subitems": [{
|
||||
"key": "key",
|
||||
"desc": "Key",
|
||||
"validator": {
|
||||
"allowBlank": true
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}]
|
||||
@@ -1,23 +0,0 @@
|
||||
[RustDesk_Server_HBBR]
|
||||
title="RustDesk Server (HBBR_TCP)"
|
||||
desc="RustDesk Server"
|
||||
port_forward="yes"
|
||||
dst.ports="21117/tcp"
|
||||
|
||||
[RustDesk_Server_HBBS_TCP]
|
||||
title="RustDesk Server (HBBS_TCP)"
|
||||
desc="RustDesk Server"
|
||||
port_forward="yes"
|
||||
dst.ports="21116/tcp"
|
||||
|
||||
[RustDesk_Server_HBBS_UDP]
|
||||
title="RustDesk Server (HBBS_UDP)"
|
||||
desc="RustDesk Server"
|
||||
port_forward="yes"
|
||||
dst.ports="21116/udp"
|
||||
|
||||
[RustDesk_Server_NAT_TCP]
|
||||
title="RustDesk Server (NAT_TCP)"
|
||||
desc="RustDesk Server"
|
||||
port_forward="yes"
|
||||
dst.ports="21115/tcp"
|
||||
@@ -1,167 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
PACKAGE_NAME="$SYNOPKG_PKGNAME"
|
||||
PACKAGE_BASE="/var/packages/${PACKAGE_NAME}/target"
|
||||
PACKAGE_SSS="/var/packages/${PACKAGE_NAME}/scripts/start-stop-status"
|
||||
|
||||
SERVICETOOL="/usr/syno/bin/servicetool"
|
||||
GETKEYVALUE="/usr/syno/bin/synogetkeyvalue"
|
||||
SETKEYVALUE="/usr/syno/bin/synosetkeyvalue"
|
||||
FWFILENAME="RustDesk_Server.sc"
|
||||
|
||||
[ "${hbbr_port}" == "" ] && hbbr_port="21117"
|
||||
[ "${hbbs_port}" == "" ] && hbbs_port="21116"
|
||||
[ "${key}" == "" ] && key=""
|
||||
[ "${email}" == "" ] && email=""
|
||||
nat_port=`expr ${hbbs_port} - 1`
|
||||
|
||||
preinst() {
|
||||
exit 0
|
||||
}
|
||||
|
||||
postinst() {
|
||||
if [ "${SYNOPKG_PKG_STATUS}" == "INSTALL" ]; then
|
||||
# 导入另一个RustDesk服务器数据
|
||||
import_db="false"
|
||||
import_all="false"
|
||||
if [ "${rds_old_import_all}" == "true" ]; then
|
||||
rds_old_import_db="true"
|
||||
import_all="true"
|
||||
elif [ "${rds_import_all}" == "true" ]; then
|
||||
rds_import_db="true"
|
||||
import_all="true"
|
||||
fi
|
||||
if [ "${rds_old_import_db}" == "true" ]; then
|
||||
import_db="true"
|
||||
PACKAGE_IMPORT_DIR="/var/packages/RustDesk_Server"
|
||||
elif [ "${rds_import_db}" == "true" ]; then
|
||||
import_db="true"
|
||||
PACKAGE_IMPORT_DIR="/var/packages/RustDesk Server"
|
||||
fi
|
||||
if [ "${import_db}" == "true" ]; then
|
||||
[ -x "${PACKAGE_IMPORT_DIR}/scripts/start-stop-status" ] \
|
||||
&& SYNOPKG_PKGNAME="RustDesk Server" "${PACKAGE_IMPORT_DIR}/scripts/start-stop-status" stop 2>&1
|
||||
[ -f "${PACKAGE_IMPORT_DIR}/enabled" ] && rm -f "${PACKAGE_IMPORT_DIR}/enabled"
|
||||
[ -d "${PACKAGE_IMPORT_DIR}/target/hbbs.db" ] && cp -prf "${PACKAGE_IMPORT_DIR}/target/hbbs.db" "${PACKAGE_BASE}"
|
||||
fi
|
||||
if [ "${import_all}" == "true" ]; then
|
||||
[ -d "${PACKAGE_IMPORT_DIR}/target/logs" ] && cp -prf "${PACKAGE_IMPORT_DIR}/target/logs" "${PACKAGE_BASE}"
|
||||
fi
|
||||
|
||||
# 添加应用配置
|
||||
sed -i "s/relay port: 21117/relay port: ${hbbr_port}/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/ID\/rendezvous port: 21116/ID\/rendezvous port: ${hbbs_port}/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/NAT test port: 21115/NAT test port: ${nat_port}/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/Key: ()/Key: (${key})/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/Email: ()/Email: (${email})/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/21117/${hbbr_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}"
|
||||
sed -i "s/21116/${hbbs_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}"
|
||||
sed -i "s/21115/${nat_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}"
|
||||
sed -i "s/port=[^ ]*/port=${hbbr_port}/g" "${PACKAGE_BASE}/config/hbbr.conf"
|
||||
sed -i "s/port=[^ ]*/port=${hbbs_port}/g" "${PACKAGE_BASE}/config/hbbs.conf"
|
||||
sed -i "s/key=[^ ]*/key=${key}/g" "${PACKAGE_BASE}/config/hbbs.conf"
|
||||
sed -i "s/email=[^ ]*/email=${email}/g" "${PACKAGE_BASE}/config/hbbs.conf"
|
||||
|
||||
# 添加防火墙配置
|
||||
cat "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}" >"/tmp/${FWFILENAME}"
|
||||
${SERVICETOOL} --install-configure-file --package "/tmp/${FWFILENAME}" >/dev/null
|
||||
rm -f "/tmp/${FWFILENAME}"
|
||||
|
||||
# 设置文件权限
|
||||
chmod -R 755 "${PACKAGE_BASE}"/*
|
||||
chmod -R 755 "/var/packages/${PACKAGE_NAME}/scripts"/*
|
||||
chmod -R 755 "/var/packages/${PACKAGE_NAME}/WIZARD_UIFILES"/*
|
||||
chmod 644 "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
preuninst() {
|
||||
# 停用套件
|
||||
"${PACKAGE_SSS}" stop
|
||||
|
||||
# 删除防火墙配置
|
||||
if [ "${SYNOPKG_PKG_STATUS}" == "UNINSTALL" ]; then
|
||||
${SERVICETOOL} --remove-configure-file --package "${FWFILENAME}" >/dev/null
|
||||
fi
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
postuninst() {
|
||||
# 删除不必要的目录...
|
||||
if [ -d "/usr/syno/etc/packages/${PACKAGE_NAME}" ]; then
|
||||
rm -rf "/usr/syno/etc/packages/${PACKAGE_NAME}"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
preupgrade() {
|
||||
# 停用套件
|
||||
"${PACKAGE_SSS}" stop
|
||||
|
||||
# Not working yet...
|
||||
# # 检索旧设置...
|
||||
# hbbr_port=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbr.conf" port`
|
||||
# hbbs_port=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbs.conf" port`
|
||||
# sed -i "s/21117/${hbbr_port}/" "/var/packages/${PACKAGE_NAME}/WIZARD_UIFILES/upgrade_uifile"
|
||||
# sed -i "s/21116/${hbbs_port}/" "/var/packages/${PACKAGE_NAME}/WIZARD_UIFILES/upgrade_uifile"
|
||||
## Not working yet...
|
||||
|
||||
# 备份数据文件...
|
||||
if [ -d "${SYNOPKG_PKGDEST}" ]; then
|
||||
DIRS4BACKUP="data logs hbbs.db config"
|
||||
for DIR in $DIRS4BACKUP; do
|
||||
if [ -d "${SYNOPKG_PKGDEST}/${DIR}" ]; then
|
||||
mkdir -p "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}"
|
||||
mv "${SYNOPKG_PKGDEST}/${DIR}"/* "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}"
|
||||
rmdir "${SYNOPKG_PKGDEST}/${DIR}"
|
||||
elif [ -f "${SYNOPKG_PKGDEST}/${DIR}" ]; then
|
||||
mv "${SYNOPKG_PKGDEST}/${DIR}" "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
postupgrade() {
|
||||
# 恢复数据文件...
|
||||
if [ -d "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade" ]; then
|
||||
for DIR in `ls "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade"`
|
||||
do
|
||||
if [ -d "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}" ]; then
|
||||
[ ! -d "${SYNOPKG_PKGDEST}/${DIR}" ] && mkdir "${SYNOPKG_PKGDEST}/${DIR}"
|
||||
mv "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}"/* "${SYNOPKG_PKGDEST}/${DIR}"
|
||||
rmdir "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}"
|
||||
elif [ -f "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}" ]; then
|
||||
mv "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade/${DIR}" "${SYNOPKG_PKGDEST}"
|
||||
fi
|
||||
done
|
||||
rmdir "${SYNOPKG_PKGDEST}/../${PACKAGE_NAME}_upgrade"
|
||||
fi
|
||||
|
||||
# 恢复设置...
|
||||
hbbr_port=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbr.conf" port` >>/tmp/wakko.txt
|
||||
hbbs_port=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbs.conf" port` >>/tmp/wakko.txt
|
||||
nat_port=`expr ${hbbs_port} - 1`
|
||||
key=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbs.conf" key` >>/tmp/wakko.txt
|
||||
email=`${GETKEYVALUE} "${PACKAGE_BASE}/config/hbbs.conf" email` >>/tmp/wakko.txt
|
||||
sed -i "s/relay port: 21117/relay port: ${hbbr_port}/" "/var/packages/${PACKAGE_NAME}/INFO" >>/tmp/wakko.txt
|
||||
sed -i "s/ID\/rendezvous port: 21116/ID\/rendezvous port: ${hbbs_port}/" "/var/packages/${PACKAGE_NAME}/INFO" >>/tmp/wakko.txt
|
||||
sed -i "s/NAT test port: 21115/NAT test port: ${nat_port}/" "/var/packages/${PACKAGE_NAME}/INFO" >>/tmp/wakko.txt
|
||||
sed -i "s/Key: ()/Key: (${key})/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/Email: ()/Email: (${email})/" "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
sed -i "s/21117/${hbbr_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}" >>/tmp/wakko.txt
|
||||
sed -i "s/21116/${hbbs_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}" >>/tmp/wakko.txt
|
||||
sed -i "s/21115/${nat_port}/" "/var/packages/${PACKAGE_NAME}/scripts/${FWFILENAME}" >>/tmp/wakko.txt
|
||||
|
||||
# 设置文件权限
|
||||
chmod -R 755 "/var/packages/${PACKAGE_NAME}/scripts"/*
|
||||
chmod -R 755 "/var/packages/${PACKAGE_NAME}/WIZARD_UIFILES"/*
|
||||
chmod 644 "/var/packages/${PACKAGE_NAME}/INFO"
|
||||
|
||||
exit 0
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "`dirname \"$0\"`/installer"
|
||||
`basename "$0"` >$SYNOPKG_TEMP_LOGFILE
|
||||
@@ -1,158 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
|
||||
sError="ERROR: "
|
||||
[ ! -z "$SYNOPKG_PKGNAME" ] && sError="<br />${sError}"
|
||||
TIMEOUT=120
|
||||
PACKAGE_NAME="RustDesk Server"
|
||||
PACKAGE_BASE="/var/packages/${PACKAGE_NAME}/target"
|
||||
HBBR_BIN="${PACKAGE_BASE}/bin/hbbr"
|
||||
HBBR_PORT=`synogetkeyvalue "${PACKAGE_BASE}/config/hbbr.conf" port`
|
||||
HBBR_LOG="/var/log/hbbr.log"
|
||||
HBBS_BIN="${PACKAGE_BASE}/bin/hbbs"
|
||||
HBBS_PORT=`synogetkeyvalue "${PACKAGE_BASE}/config/hbbs.conf" port`
|
||||
KEY=`synogetkeyvalue "${PACKAGE_BASE}/config/hbbs.conf" key`
|
||||
EMAIL=`synogetkeyvalue "${PACKAGE_BASE}/config/hbbs.conf" email`
|
||||
HBBS_LOG="/var/log/hbbs.log"
|
||||
PACKAGE_ENABLED="/var/packages/${PACKAGE_NAME}/enabled"
|
||||
PS_CMD="/bin/ps -w"
|
||||
DSM_MAJORVERSION=`synogetkeyvalue /etc.defaults/VERSION majorversion`
|
||||
if [[ $DSM_MAJORVERSION -gt 5 ]]; then
|
||||
PS_CMD="$PS_CMD -x"
|
||||
fi
|
||||
|
||||
CheckIfDaemonAlive() {
|
||||
local PID="$1"
|
||||
PROCESS_ALIVE="0"
|
||||
[ -z "$PID" ] && return 1
|
||||
|
||||
kill -0 "$PID"
|
||||
[ "0" == "$?" ] && PROCESS_ALIVE="1"
|
||||
}
|
||||
|
||||
running_hbbr() {
|
||||
local PID=$(${PS_CMD} | sed -e 's/^[ \t]*//' | grep -v grep | grep hbbr | grep "${PACKAGE_NAME}" | head -n1 | cut -f1 -d' ')
|
||||
CheckIfDaemonAlive $PID
|
||||
[ "0" == "$PROCESS_ALIVE" ] && return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
running_hbbs() {
|
||||
local PID=$(${PS_CMD} | sed -e 's/^[ \t]*//' | grep -v grep | grep hbbs | grep "${PACKAGE_NAME}" | head -n1 | cut -f1 -d' ')
|
||||
CheckIfDaemonAlive $PID
|
||||
[ "0" == "$PROCESS_ALIVE" ] && return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
start() {
|
||||
[ "$SYNOPKG_TEMP_LOGFILE" == "" ] && SYNOPKG_TEMP_LOGFILE="/var/log/rustdeskserver.start.log"
|
||||
LANG=C cd "$PACKAGE_BASE" && (nohup "$HBBR_BIN" -p $HBBR_PORT -k "$KEY" -m "$EMAIL" > "$HBBR_LOG" 2>&1 &) && (nohup "$HBBS_BIN" -p $HBBS_PORT -k "$KEY" -m "$EMAIL" > "$HBBS_LOG" 2>&1 &)
|
||||
|
||||
|
||||
i=0
|
||||
while true; do
|
||||
if ! running_hbbr || ! running_hbbs ; then
|
||||
# echo "WAIT: ${i}s of ${TIMEOUT}s"
|
||||
sleep 5s
|
||||
i=$((i+5))
|
||||
else
|
||||
break
|
||||
fi
|
||||
[ $i -ge $TIMEOUT ] && break
|
||||
done
|
||||
|
||||
# 检查hbbr进程状态
|
||||
if ! running_hbbr ; then
|
||||
echo -e "${sError}hbbr process not running" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
stop
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查hbbs进程状态
|
||||
if ! running_hbbs ; then
|
||||
echo -e "${sError}hbbs process not running" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
stop
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
stop() {
|
||||
[ "$SYNOPKG_TEMP_LOGFILE" == "" ] && SYNOPKG_TEMP_LOGFILE="/var/log/rustdeskserver.stop.log"
|
||||
# 检查hbbr进程状态
|
||||
if running_hbbr ; then
|
||||
local PID=$(${PS_CMD} | sed -e 's/^[ \t]*//' | grep -v grep | grep hbbr | grep "${PACKAGE_NAME}" | head -n1 | cut -f1 -d' ')
|
||||
[ -z "$PID" ] && return 0
|
||||
kill -15 $PID
|
||||
sleep 5s
|
||||
|
||||
# 检查hbbr进程状态
|
||||
if running_hbbr ; then
|
||||
kill -9 $PID
|
||||
sleep 5s
|
||||
if running_hbbr ; then
|
||||
echo "${sError}Failed to kill hbbr process(pid=$PID)!" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查hbbs进程状态
|
||||
if running_hbbs ; then
|
||||
local PID=$(${PS_CMD} | sed -e 's/^[ \t]*//' | grep -v grep | grep hbbs | grep "${PACKAGE_NAME}" | head -n1 | cut -f1 -d' ')
|
||||
[ -z "$PID" ] && return 0
|
||||
kill -15 $PID
|
||||
sleep 5s
|
||||
|
||||
# 检查hbbs进程状态
|
||||
if running_hbbs ; then
|
||||
kill -9 $PID
|
||||
sleep 5s
|
||||
if running_hbbs ; then
|
||||
echo "${sError}无法关闭hbbs进程 (pid=$PID)!" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
case $1 in
|
||||
start)
|
||||
# 启动服务器
|
||||
start
|
||||
exit $?
|
||||
;;
|
||||
stop)
|
||||
# 关闭服务器
|
||||
stop
|
||||
exit $?
|
||||
;;
|
||||
status)
|
||||
# 检查套件开关
|
||||
if [ ! -f "${PACKAGE_ENABLED}" ]; then
|
||||
echo "${sError}package not started" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 检查hbbr进程状态
|
||||
if ! running_hbbr ; then
|
||||
echo "${sError}hbbr process killed" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查hbbs进程状态
|
||||
if ! running_hbbs ; then
|
||||
echo "${sError}hbbs process killed" | tee -a $SYNOPKG_TEMP_LOGFILE
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
;;
|
||||
log)
|
||||
echo "$PACKAGE_BASE/logs/server.log"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
191
src/common.rs
Normal file
191
src/common.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
use clap::App;
|
||||
use hbb_common::{
|
||||
anyhow::{Context, Result},
|
||||
log, 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.get(0) {
|
||||
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 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 {
|
||||
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::hangup())?;
|
||||
let hangup = s.recv();
|
||||
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! {
|
||||
_ = hangup => {
|
||||
log::info!("signal hangup");
|
||||
}
|
||||
_ = 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!();
|
||||
}
|
||||
181
src/database.rs
Normal file
181
src/database.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
43
src/hbbr.rs
43
src/hbbr.rs
@@ -1,34 +1,45 @@
|
||||
use clap::App;
|
||||
mod common;
|
||||
mod relay_server;
|
||||
use hbb_common::{env_logger::*, ResultType};
|
||||
use flexi_logger::*;
|
||||
use hbb_common::{config::RELAY_PORT, ResultType};
|
||||
use relay_server::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
mod lic;
|
||||
mod version;
|
||||
|
||||
fn main() -> ResultType<()> {
|
||||
init_from_env(Env::default().filter_or(DEFAULT_FILTER_ENV, "info"));
|
||||
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={})] 'Sets the listening port'
|
||||
"-p, --port=[NUMBER(default={RELAY_PORT})] 'Sets the listening port'
|
||||
-k, --key=[KEY] 'Only allow the client with the same key'
|
||||
{}
|
||||
",
|
||||
DEFAULT_PORT,
|
||||
lic::EMAIL_ARG
|
||||
);
|
||||
let matches = App::new("hbbr")
|
||||
.version(hbbs::VERSION)
|
||||
.author("CarrieZ Studio<info@rustdesk.com>")
|
||||
.version(version::VERSION)
|
||||
.author("Purslane Ltd. <info@rustdesk.com>")
|
||||
.about("RustDesk Relay Server")
|
||||
.args_from_usage(&args)
|
||||
.get_matches();
|
||||
if !lic::check_lic(matches.value_of("email").unwrap_or(""), hbbs::VERSION) {
|
||||
return Ok(());
|
||||
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;
|
||||
}
|
||||
}
|
||||
let stop: Arc<Mutex<bool>> = Default::default();
|
||||
start(
|
||||
matches.value_of("port").unwrap_or(DEFAULT_PORT),
|
||||
matches.value_of("key").unwrap_or(""),
|
||||
stop,
|
||||
matches.value_of("port").unwrap_or(&port.to_string()),
|
||||
matches
|
||||
.value_of("key")
|
||||
.unwrap_or(&std::env::var("KEY").unwrap_or_default()),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod rendezvous_server;
|
||||
mod sled_async;
|
||||
pub use rendezvous_server::*;
|
||||
use sled_async::*;
|
||||
pub mod common;
|
||||
mod database;
|
||||
mod peer;
|
||||
mod version;
|
||||
pub use version::*;
|
||||
|
||||
170
src/lic.rs
170
src/lic.rs
@@ -1,170 +0,0 @@
|
||||
use hbb_common::{bail, log, ResultType, rand::{self, Rng}};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::io::prelude::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, PartialEq, Default, Serialize, Deserialize, Clone)]
|
||||
pub struct Machine {
|
||||
#[serde(default)]
|
||||
hostname: String,
|
||||
#[serde(default)]
|
||||
uid: String,
|
||||
#[serde(default)]
|
||||
mac: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Default, Serialize, Deserialize, Clone)]
|
||||
pub struct Post {
|
||||
#[serde(default)]
|
||||
machine: String,
|
||||
#[serde(default)]
|
||||
email: String,
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
#[serde(default)]
|
||||
next_check_time: u64,
|
||||
#[serde(default)]
|
||||
nonce: String,
|
||||
#[serde(default)]
|
||||
tip: String,
|
||||
}
|
||||
|
||||
const LICENSE_FILE: &'static str = ".license.txt";
|
||||
|
||||
pub fn check_lic(email: &str, version: &str) -> bool {
|
||||
if email.is_empty() {
|
||||
log::error!("Registered email required (-m option). Please pay and register on https://rustdesk.com/server.");
|
||||
return false;
|
||||
}
|
||||
|
||||
let is_docker = std::path::Path::new("/.dockerenv").exists();
|
||||
let machine = if is_docker { "".to_owned() } else { get_lic() };
|
||||
if !is_docker {
|
||||
let path = Path::new(LICENSE_FILE);
|
||||
if Path::is_file(&path) {
|
||||
let contents = std::fs::read_to_string(&path).unwrap_or("".to_owned());
|
||||
if verify(&contents, &machine) {
|
||||
async_check_email(&machine, email, version, 0);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match check_email(machine.clone(), email.to_owned(), version.to_owned()) {
|
||||
Ok(v) => {
|
||||
async_check_email(&machine, email, version, v);
|
||||
return true;
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn async_check_email(machine: &str, email: &str, version: &str, wait: u64) {
|
||||
let machine = machine.to_owned();
|
||||
let email = email.to_owned();
|
||||
let version = version.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
let mut wait = wait;
|
||||
loop {
|
||||
let machine = machine.clone();
|
||||
let email = email.clone();
|
||||
let version = version.clone();
|
||||
std::thread::sleep(std::time::Duration::from_secs(wait));
|
||||
match check_email(machine, email, version) {
|
||||
Ok(v) => {
|
||||
wait = v;
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
std::process::exit(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn write_lic(lic: &str) {
|
||||
if let Ok(mut f) = std::fs::File::create(LICENSE_FILE) {
|
||||
f.write_all(lic.as_bytes()).ok();
|
||||
f.sync_all().ok();
|
||||
}
|
||||
}
|
||||
|
||||
fn check_email(machine: String, email: String, version: String) -> ResultType<u64> {
|
||||
log::info!("Checking email with the license server ...");
|
||||
let mut rng = rand::thread_rng();
|
||||
let nonce: usize = rng.gen();
|
||||
let nonce = nonce.to_string();
|
||||
let resp = minreq::post("http://rustdesk.com/api/check-email")
|
||||
.with_body(
|
||||
serde_json::to_string(&Post {
|
||||
machine: machine.clone(),
|
||||
version,
|
||||
email,
|
||||
nonce: nonce.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.send()?;
|
||||
if resp.reason_phrase == "OK" {
|
||||
let p: Post = serde_json::from_str(&resp.as_str()?)?;
|
||||
if !p.status.is_empty() {
|
||||
std::fs::remove_file(LICENSE_FILE).ok();
|
||||
bail!("{}", p.status);
|
||||
}
|
||||
if p.nonce.is_empty() {
|
||||
bail!("Verification failure: nonce required");
|
||||
}
|
||||
if !verify(&p.nonce, &nonce) {
|
||||
bail!("Verification failure: nonce mismatch");
|
||||
}
|
||||
if !machine.is_empty() {
|
||||
if !verify(&p.machine, &machine) {
|
||||
bail!("Verification failure");
|
||||
}
|
||||
write_lic(&p.machine);
|
||||
}
|
||||
log::info!("License OK");
|
||||
if !p.tip.is_empty() {
|
||||
log::info!("{}", p.tip);
|
||||
}
|
||||
let mut wait = p.next_check_time;
|
||||
if wait == 0 {
|
||||
wait = 3600 * 24 * 30;
|
||||
}
|
||||
|
||||
Ok(wait)
|
||||
} else {
|
||||
bail!("Server error: {}", resp.reason_phrase);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_lic() -> String {
|
||||
let hostname = whoami::hostname();
|
||||
let uid = machine_uid::get().unwrap_or("".to_owned());
|
||||
let mac = if let Ok(Some(ma)) = mac_address::get_mac_address() {
|
||||
base64::encode(ma.bytes())
|
||||
} else {
|
||||
"".to_owned()
|
||||
};
|
||||
serde_json::to_string(&Machine { hostname, uid, mac }).unwrap()
|
||||
}
|
||||
|
||||
fn verify(enc_str: &str, msg: &str) -> bool {
|
||||
if let Ok(data) = base64::decode(enc_str) {
|
||||
let key =
|
||||
b"\xf1T\xc0\x1c\xffee\x86,S*\xd9.\x91\xcd\x85\x12:\xec\xa9 \x99:\x8a\xa2S\x1f Yy\x93R";
|
||||
cryptoxide::ed25519::verify(msg.as_bytes(), &key[..], &data)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub const EMAIL_ARG: &'static str =
|
||||
"-m, --email=[EMAIL] 'Sets your email address registered with RustDesk'";
|
||||
87
src/main.rs
87
src/main.rs
@@ -1,83 +1,36 @@
|
||||
// https://tools.ietf.org/rfc/rfc5128.txt
|
||||
// https://blog.csdn.net/bytxl/article/details/44344855
|
||||
|
||||
use clap::App;
|
||||
use hbb_common::{env_logger::*, log, ResultType};
|
||||
use hbbs::*;
|
||||
mod lic;
|
||||
use ini::Ini;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use flexi_logger::*;
|
||||
use hbb_common::{bail, config::RENDEZVOUS_PORT, ResultType};
|
||||
use hbbs::{common::*, *};
|
||||
|
||||
const RMEM: usize = 0;
|
||||
|
||||
fn main() -> ResultType<()> {
|
||||
init_from_env(Env::default().filter_or(DEFAULT_FILTER_ENV, "info"));
|
||||
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={})] 'Sets the listening port'
|
||||
-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, seperated by colon'
|
||||
-u, --software-url=[URL] 'Sets download url of RustDesk software of newest version'
|
||||
-r, --relay-servers=[HOST] 'Sets the default relay servers, seperated by colon'
|
||||
-C, --change-id=[BOOL(default=Y)] 'Sets if support to change id'
|
||||
{}
|
||||
-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'",
|
||||
DEFAULT_PORT,
|
||||
lic::EMAIL_ARG
|
||||
);
|
||||
let matches = App::new("hbbs")
|
||||
.version(crate::VERSION)
|
||||
.author("CarrieZ Studio<info@rustdesk.com>")
|
||||
.about("RustDesk ID/Rendezvous Server")
|
||||
.args_from_usage(&args)
|
||||
.get_matches();
|
||||
let mut section = None;
|
||||
let conf; // for holding section
|
||||
if let Some(config) = matches.value_of("config") {
|
||||
if let Ok(v) = Ini::load_from_file(config) {
|
||||
conf = v;
|
||||
section = conf.section(None::<String>);
|
||||
}
|
||||
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 get_arg = |name: &str, default: &str| -> String {
|
||||
if let Some(v) = matches.value_of(name) {
|
||||
return v.to_owned();
|
||||
} else if let Some(section) = section {
|
||||
if let Some(v) = section.get(name) {
|
||||
return v.to_owned();
|
||||
}
|
||||
}
|
||||
return default.to_owned();
|
||||
};
|
||||
if !lic::check_lic(&get_arg("email", ""), crate::VERSION) {
|
||||
return Ok(());
|
||||
}
|
||||
let port = get_arg("port", DEFAULT_PORT);
|
||||
let relay_servers: Vec<String> = get_arg("relay-servers", "")
|
||||
.split(",")
|
||||
.filter(|x| !x.is_empty() && test_if_valid_server(x, "relay-server").is_ok())
|
||||
.map(|x| x.to_owned())
|
||||
.collect();
|
||||
let serial: i32 = get_arg("serial", "").parse().unwrap_or(0);
|
||||
let id_change_support: bool = get_arg("change-id", "Y").to_uppercase() == "Y";
|
||||
let rendezvous_servers: Vec<String> = get_arg("rendezvous-servers", "")
|
||||
.split(",")
|
||||
.filter(|x| !x.is_empty() && test_if_valid_server(x, "rendezvous-server").is_ok())
|
||||
.map(|x| x.to_owned())
|
||||
.collect();
|
||||
let addr = format!("0.0.0.0:{}", port);
|
||||
let addr2 = format!("0.0.0.0:{}", port.parse::<i32>().unwrap_or(0) - 1);
|
||||
log::info!("serial={}", serial);
|
||||
log::info!("rendezvous-servers={:?}", rendezvous_servers);
|
||||
let stop: Arc<Mutex<bool>> = Default::default();
|
||||
RendezvousServer::start(
|
||||
&addr,
|
||||
&addr2,
|
||||
relay_servers,
|
||||
serial,
|
||||
rendezvous_servers,
|
||||
get_arg("software-url", ""),
|
||||
&get_arg("key", ""),
|
||||
stop,
|
||||
id_change_support,
|
||||
)?;
|
||||
let rmem = get_arg("rmem").parse::<usize>().unwrap_or(RMEM);
|
||||
let serial: i32 = get_arg("serial").parse().unwrap_or(0);
|
||||
RendezvousServer::start(port, serial, &get_arg("key"), rmem)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
180
src/peer.rs
Normal file
180
src/peer.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
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 static IP_CHANGE_DUR: u64 = 180;
|
||||
pub static IP_CHANGE_DUR_X2: u64 = IP_CHANGE_DUR * 2;
|
||||
pub static DAY_SECONDS: u64 = 3600 * 24;
|
||||
pub static 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)
|
||||
}
|
||||
}
|
||||
@@ -1,930 +0,0 @@
|
||||
// This file is generated by rust-protobuf 2.10.2. Do not edit
|
||||
// @generated
|
||||
|
||||
// https://github.com/rust-lang/rust-clippy/issues/702
|
||||
#![allow(unknown_lints)]
|
||||
#![allow(clippy::all)]
|
||||
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
|
||||
#![allow(box_pointers)]
|
||||
#![allow(dead_code)]
|
||||
#![allow(missing_docs)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(trivial_casts)]
|
||||
#![allow(unsafe_code)]
|
||||
#![allow(unused_imports)]
|
||||
#![allow(unused_results)]
|
||||
//! Generated file from `message.proto`
|
||||
|
||||
use protobuf::Message as Message_imported_for_functions;
|
||||
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
|
||||
|
||||
/// Generated files are compatible only with the same version
|
||||
/// of protobuf runtime.
|
||||
// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_10_2;
|
||||
|
||||
#[derive(PartialEq,Clone,Default)]
|
||||
pub struct RegisterPeer {
|
||||
// message fields
|
||||
pub hbb_addr: ::std::string::String,
|
||||
// special fields
|
||||
pub unknown_fields: ::protobuf::UnknownFields,
|
||||
pub cached_size: ::protobuf::CachedSize,
|
||||
}
|
||||
|
||||
impl<'a> ::std::default::Default for &'a RegisterPeer {
|
||||
fn default() -> &'a RegisterPeer {
|
||||
<RegisterPeer as ::protobuf::Message>::default_instance()
|
||||
}
|
||||
}
|
||||
|
||||
impl RegisterPeer {
|
||||
pub fn new() -> RegisterPeer {
|
||||
::std::default::Default::default()
|
||||
}
|
||||
|
||||
// string hbb_addr = 1;
|
||||
|
||||
|
||||
pub fn get_hbb_addr(&self) -> &str {
|
||||
&self.hbb_addr
|
||||
}
|
||||
pub fn clear_hbb_addr(&mut self) {
|
||||
self.hbb_addr.clear();
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_hbb_addr(&mut self, v: ::std::string::String) {
|
||||
self.hbb_addr = v;
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
// If field is not initialized, it is initialized with default value first.
|
||||
pub fn mut_hbb_addr(&mut self) -> &mut ::std::string::String {
|
||||
&mut self.hbb_addr
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_hbb_addr(&mut self) -> ::std::string::String {
|
||||
::std::mem::replace(&mut self.hbb_addr, ::std::string::String::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Message for RegisterPeer {
|
||||
fn is_initialized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
while !is.eof()? {
|
||||
let (field_number, wire_type) = is.read_tag_unpack()?;
|
||||
match field_number {
|
||||
1 => {
|
||||
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.hbb_addr)?;
|
||||
},
|
||||
_ => {
|
||||
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
|
||||
},
|
||||
};
|
||||
}
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
// Compute sizes of nested messages
|
||||
#[allow(unused_variables)]
|
||||
fn compute_size(&self) -> u32 {
|
||||
let mut my_size = 0;
|
||||
if !self.hbb_addr.is_empty() {
|
||||
my_size += ::protobuf::rt::string_size(1, &self.hbb_addr);
|
||||
}
|
||||
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
|
||||
self.cached_size.set(my_size);
|
||||
my_size
|
||||
}
|
||||
|
||||
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
if !self.hbb_addr.is_empty() {
|
||||
os.write_string(1, &self.hbb_addr)?;
|
||||
}
|
||||
os.write_unknown_fields(self.get_unknown_fields())?;
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
fn get_cached_size(&self) -> u32 {
|
||||
self.cached_size.get()
|
||||
}
|
||||
|
||||
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
|
||||
&self.unknown_fields
|
||||
}
|
||||
|
||||
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
|
||||
&mut self.unknown_fields
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn (::std::any::Any) {
|
||||
self as &dyn (::std::any::Any)
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
|
||||
self as &mut dyn (::std::any::Any)
|
||||
}
|
||||
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
|
||||
self
|
||||
}
|
||||
|
||||
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
Self::descriptor_static()
|
||||
}
|
||||
|
||||
fn new() -> RegisterPeer {
|
||||
RegisterPeer::new()
|
||||
}
|
||||
|
||||
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
|
||||
};
|
||||
unsafe {
|
||||
descriptor.get(|| {
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
|
||||
"hbb_addr",
|
||||
|m: &RegisterPeer| { &m.hbb_addr },
|
||||
|m: &mut RegisterPeer| { &mut m.hbb_addr },
|
||||
));
|
||||
::protobuf::reflect::MessageDescriptor::new::<RegisterPeer>(
|
||||
"RegisterPeer",
|
||||
fields,
|
||||
file_descriptor_proto()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_instance() -> &'static RegisterPeer {
|
||||
static mut instance: ::protobuf::lazy::Lazy<RegisterPeer> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const RegisterPeer,
|
||||
};
|
||||
unsafe {
|
||||
instance.get(RegisterPeer::new)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Clear for RegisterPeer {
|
||||
fn clear(&mut self) {
|
||||
self.hbb_addr.clear();
|
||||
self.unknown_fields.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl ::std::fmt::Debug for RegisterPeer {
|
||||
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
|
||||
::protobuf::text_format::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::reflect::ProtobufValue for RegisterPeer {
|
||||
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
|
||||
::protobuf::reflect::ProtobufValueRef::Message(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq,Clone,Default)]
|
||||
pub struct PeekPeer {
|
||||
// message fields
|
||||
pub hbb_addr: ::std::string::String,
|
||||
// special fields
|
||||
pub unknown_fields: ::protobuf::UnknownFields,
|
||||
pub cached_size: ::protobuf::CachedSize,
|
||||
}
|
||||
|
||||
impl<'a> ::std::default::Default for &'a PeekPeer {
|
||||
fn default() -> &'a PeekPeer {
|
||||
<PeekPeer as ::protobuf::Message>::default_instance()
|
||||
}
|
||||
}
|
||||
|
||||
impl PeekPeer {
|
||||
pub fn new() -> PeekPeer {
|
||||
::std::default::Default::default()
|
||||
}
|
||||
|
||||
// string hbb_addr = 1;
|
||||
|
||||
|
||||
pub fn get_hbb_addr(&self) -> &str {
|
||||
&self.hbb_addr
|
||||
}
|
||||
pub fn clear_hbb_addr(&mut self) {
|
||||
self.hbb_addr.clear();
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_hbb_addr(&mut self, v: ::std::string::String) {
|
||||
self.hbb_addr = v;
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
// If field is not initialized, it is initialized with default value first.
|
||||
pub fn mut_hbb_addr(&mut self) -> &mut ::std::string::String {
|
||||
&mut self.hbb_addr
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_hbb_addr(&mut self) -> ::std::string::String {
|
||||
::std::mem::replace(&mut self.hbb_addr, ::std::string::String::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Message for PeekPeer {
|
||||
fn is_initialized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
while !is.eof()? {
|
||||
let (field_number, wire_type) = is.read_tag_unpack()?;
|
||||
match field_number {
|
||||
1 => {
|
||||
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.hbb_addr)?;
|
||||
},
|
||||
_ => {
|
||||
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
|
||||
},
|
||||
};
|
||||
}
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
// Compute sizes of nested messages
|
||||
#[allow(unused_variables)]
|
||||
fn compute_size(&self) -> u32 {
|
||||
let mut my_size = 0;
|
||||
if !self.hbb_addr.is_empty() {
|
||||
my_size += ::protobuf::rt::string_size(1, &self.hbb_addr);
|
||||
}
|
||||
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
|
||||
self.cached_size.set(my_size);
|
||||
my_size
|
||||
}
|
||||
|
||||
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
if !self.hbb_addr.is_empty() {
|
||||
os.write_string(1, &self.hbb_addr)?;
|
||||
}
|
||||
os.write_unknown_fields(self.get_unknown_fields())?;
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
fn get_cached_size(&self) -> u32 {
|
||||
self.cached_size.get()
|
||||
}
|
||||
|
||||
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
|
||||
&self.unknown_fields
|
||||
}
|
||||
|
||||
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
|
||||
&mut self.unknown_fields
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn (::std::any::Any) {
|
||||
self as &dyn (::std::any::Any)
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
|
||||
self as &mut dyn (::std::any::Any)
|
||||
}
|
||||
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
|
||||
self
|
||||
}
|
||||
|
||||
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
Self::descriptor_static()
|
||||
}
|
||||
|
||||
fn new() -> PeekPeer {
|
||||
PeekPeer::new()
|
||||
}
|
||||
|
||||
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
|
||||
};
|
||||
unsafe {
|
||||
descriptor.get(|| {
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
|
||||
"hbb_addr",
|
||||
|m: &PeekPeer| { &m.hbb_addr },
|
||||
|m: &mut PeekPeer| { &mut m.hbb_addr },
|
||||
));
|
||||
::protobuf::reflect::MessageDescriptor::new::<PeekPeer>(
|
||||
"PeekPeer",
|
||||
fields,
|
||||
file_descriptor_proto()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_instance() -> &'static PeekPeer {
|
||||
static mut instance: ::protobuf::lazy::Lazy<PeekPeer> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const PeekPeer,
|
||||
};
|
||||
unsafe {
|
||||
instance.get(PeekPeer::new)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Clear for PeekPeer {
|
||||
fn clear(&mut self) {
|
||||
self.hbb_addr.clear();
|
||||
self.unknown_fields.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl ::std::fmt::Debug for PeekPeer {
|
||||
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
|
||||
::protobuf::text_format::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::reflect::ProtobufValue for PeekPeer {
|
||||
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
|
||||
::protobuf::reflect::ProtobufValueRef::Message(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq,Clone,Default)]
|
||||
pub struct PeekPeerResponse {
|
||||
// message fields
|
||||
pub socket_addr: ::std::vec::Vec<u8>,
|
||||
// special fields
|
||||
pub unknown_fields: ::protobuf::UnknownFields,
|
||||
pub cached_size: ::protobuf::CachedSize,
|
||||
}
|
||||
|
||||
impl<'a> ::std::default::Default for &'a PeekPeerResponse {
|
||||
fn default() -> &'a PeekPeerResponse {
|
||||
<PeekPeerResponse as ::protobuf::Message>::default_instance()
|
||||
}
|
||||
}
|
||||
|
||||
impl PeekPeerResponse {
|
||||
pub fn new() -> PeekPeerResponse {
|
||||
::std::default::Default::default()
|
||||
}
|
||||
|
||||
// bytes socket_addr = 1;
|
||||
|
||||
|
||||
pub fn get_socket_addr(&self) -> &[u8] {
|
||||
&self.socket_addr
|
||||
}
|
||||
pub fn clear_socket_addr(&mut self) {
|
||||
self.socket_addr.clear();
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_socket_addr(&mut self, v: ::std::vec::Vec<u8>) {
|
||||
self.socket_addr = v;
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
// If field is not initialized, it is initialized with default value first.
|
||||
pub fn mut_socket_addr(&mut self) -> &mut ::std::vec::Vec<u8> {
|
||||
&mut self.socket_addr
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_socket_addr(&mut self) -> ::std::vec::Vec<u8> {
|
||||
::std::mem::replace(&mut self.socket_addr, ::std::vec::Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Message for PeekPeerResponse {
|
||||
fn is_initialized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
while !is.eof()? {
|
||||
let (field_number, wire_type) = is.read_tag_unpack()?;
|
||||
match field_number {
|
||||
1 => {
|
||||
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.socket_addr)?;
|
||||
},
|
||||
_ => {
|
||||
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
|
||||
},
|
||||
};
|
||||
}
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
// Compute sizes of nested messages
|
||||
#[allow(unused_variables)]
|
||||
fn compute_size(&self) -> u32 {
|
||||
let mut my_size = 0;
|
||||
if !self.socket_addr.is_empty() {
|
||||
my_size += ::protobuf::rt::bytes_size(1, &self.socket_addr);
|
||||
}
|
||||
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
|
||||
self.cached_size.set(my_size);
|
||||
my_size
|
||||
}
|
||||
|
||||
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
if !self.socket_addr.is_empty() {
|
||||
os.write_bytes(1, &self.socket_addr)?;
|
||||
}
|
||||
os.write_unknown_fields(self.get_unknown_fields())?;
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
fn get_cached_size(&self) -> u32 {
|
||||
self.cached_size.get()
|
||||
}
|
||||
|
||||
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
|
||||
&self.unknown_fields
|
||||
}
|
||||
|
||||
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
|
||||
&mut self.unknown_fields
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn (::std::any::Any) {
|
||||
self as &dyn (::std::any::Any)
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
|
||||
self as &mut dyn (::std::any::Any)
|
||||
}
|
||||
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
|
||||
self
|
||||
}
|
||||
|
||||
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
Self::descriptor_static()
|
||||
}
|
||||
|
||||
fn new() -> PeekPeerResponse {
|
||||
PeekPeerResponse::new()
|
||||
}
|
||||
|
||||
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
|
||||
};
|
||||
unsafe {
|
||||
descriptor.get(|| {
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
|
||||
"socket_addr",
|
||||
|m: &PeekPeerResponse| { &m.socket_addr },
|
||||
|m: &mut PeekPeerResponse| { &mut m.socket_addr },
|
||||
));
|
||||
::protobuf::reflect::MessageDescriptor::new::<PeekPeerResponse>(
|
||||
"PeekPeerResponse",
|
||||
fields,
|
||||
file_descriptor_proto()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_instance() -> &'static PeekPeerResponse {
|
||||
static mut instance: ::protobuf::lazy::Lazy<PeekPeerResponse> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const PeekPeerResponse,
|
||||
};
|
||||
unsafe {
|
||||
instance.get(PeekPeerResponse::new)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Clear for PeekPeerResponse {
|
||||
fn clear(&mut self) {
|
||||
self.socket_addr.clear();
|
||||
self.unknown_fields.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl ::std::fmt::Debug for PeekPeerResponse {
|
||||
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
|
||||
::protobuf::text_format::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::reflect::ProtobufValue for PeekPeerResponse {
|
||||
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
|
||||
::protobuf::reflect::ProtobufValueRef::Message(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq,Clone,Default)]
|
||||
pub struct Message {
|
||||
// message oneof groups
|
||||
pub union: ::std::option::Option<Message_oneof_union>,
|
||||
// special fields
|
||||
pub unknown_fields: ::protobuf::UnknownFields,
|
||||
pub cached_size: ::protobuf::CachedSize,
|
||||
}
|
||||
|
||||
impl<'a> ::std::default::Default for &'a Message {
|
||||
fn default() -> &'a Message {
|
||||
<Message as ::protobuf::Message>::default_instance()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,PartialEq,Debug)]
|
||||
pub enum Message_oneof_union {
|
||||
register_peer(RegisterPeer),
|
||||
peek_peer(PeekPeer),
|
||||
peek_peer_response(PeekPeerResponse),
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn new() -> Message {
|
||||
::std::default::Default::default()
|
||||
}
|
||||
|
||||
// .hbb.RegisterPeer register_peer = 6;
|
||||
|
||||
|
||||
pub fn get_register_peer(&self) -> &RegisterPeer {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::register_peer(ref v)) => v,
|
||||
_ => RegisterPeer::default_instance(),
|
||||
}
|
||||
}
|
||||
pub fn clear_register_peer(&mut self) {
|
||||
self.union = ::std::option::Option::None;
|
||||
}
|
||||
|
||||
pub fn has_register_peer(&self) -> bool {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::register_peer(..)) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_register_peer(&mut self, v: RegisterPeer) {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::register_peer(v))
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
pub fn mut_register_peer(&mut self) -> &mut RegisterPeer {
|
||||
if let ::std::option::Option::Some(Message_oneof_union::register_peer(_)) = self.union {
|
||||
} else {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::register_peer(RegisterPeer::new()));
|
||||
}
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::register_peer(ref mut v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_register_peer(&mut self) -> RegisterPeer {
|
||||
if self.has_register_peer() {
|
||||
match self.union.take() {
|
||||
::std::option::Option::Some(Message_oneof_union::register_peer(v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
} else {
|
||||
RegisterPeer::new()
|
||||
}
|
||||
}
|
||||
|
||||
// .hbb.PeekPeer peek_peer = 7;
|
||||
|
||||
|
||||
pub fn get_peek_peer(&self) -> &PeekPeer {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer(ref v)) => v,
|
||||
_ => PeekPeer::default_instance(),
|
||||
}
|
||||
}
|
||||
pub fn clear_peek_peer(&mut self) {
|
||||
self.union = ::std::option::Option::None;
|
||||
}
|
||||
|
||||
pub fn has_peek_peer(&self) -> bool {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer(..)) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_peek_peer(&mut self, v: PeekPeer) {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer(v))
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
pub fn mut_peek_peer(&mut self) -> &mut PeekPeer {
|
||||
if let ::std::option::Option::Some(Message_oneof_union::peek_peer(_)) = self.union {
|
||||
} else {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer(PeekPeer::new()));
|
||||
}
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer(ref mut v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_peek_peer(&mut self) -> PeekPeer {
|
||||
if self.has_peek_peer() {
|
||||
match self.union.take() {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer(v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
} else {
|
||||
PeekPeer::new()
|
||||
}
|
||||
}
|
||||
|
||||
// .hbb.PeekPeerResponse peek_peer_response = 8;
|
||||
|
||||
|
||||
pub fn get_peek_peer_response(&self) -> &PeekPeerResponse {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer_response(ref v)) => v,
|
||||
_ => PeekPeerResponse::default_instance(),
|
||||
}
|
||||
}
|
||||
pub fn clear_peek_peer_response(&mut self) {
|
||||
self.union = ::std::option::Option::None;
|
||||
}
|
||||
|
||||
pub fn has_peek_peer_response(&self) -> bool {
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer_response(..)) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// Param is passed by value, moved
|
||||
pub fn set_peek_peer_response(&mut self, v: PeekPeerResponse) {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer_response(v))
|
||||
}
|
||||
|
||||
// Mutable pointer to the field.
|
||||
pub fn mut_peek_peer_response(&mut self) -> &mut PeekPeerResponse {
|
||||
if let ::std::option::Option::Some(Message_oneof_union::peek_peer_response(_)) = self.union {
|
||||
} else {
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer_response(PeekPeerResponse::new()));
|
||||
}
|
||||
match self.union {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer_response(ref mut v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Take field
|
||||
pub fn take_peek_peer_response(&mut self) -> PeekPeerResponse {
|
||||
if self.has_peek_peer_response() {
|
||||
match self.union.take() {
|
||||
::std::option::Option::Some(Message_oneof_union::peek_peer_response(v)) => v,
|
||||
_ => panic!(),
|
||||
}
|
||||
} else {
|
||||
PeekPeerResponse::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Message for Message {
|
||||
fn is_initialized(&self) -> bool {
|
||||
if let Some(Message_oneof_union::register_peer(ref v)) = self.union {
|
||||
if !v.is_initialized() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(Message_oneof_union::peek_peer(ref v)) = self.union {
|
||||
if !v.is_initialized() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(Message_oneof_union::peek_peer_response(ref v)) = self.union {
|
||||
if !v.is_initialized() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
while !is.eof()? {
|
||||
let (field_number, wire_type) = is.read_tag_unpack()?;
|
||||
match field_number {
|
||||
6 => {
|
||||
if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
|
||||
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
|
||||
}
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::register_peer(is.read_message()?));
|
||||
},
|
||||
7 => {
|
||||
if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
|
||||
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
|
||||
}
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer(is.read_message()?));
|
||||
},
|
||||
8 => {
|
||||
if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
|
||||
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
|
||||
}
|
||||
self.union = ::std::option::Option::Some(Message_oneof_union::peek_peer_response(is.read_message()?));
|
||||
},
|
||||
_ => {
|
||||
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
|
||||
},
|
||||
};
|
||||
}
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
// Compute sizes of nested messages
|
||||
#[allow(unused_variables)]
|
||||
fn compute_size(&self) -> u32 {
|
||||
let mut my_size = 0;
|
||||
if let ::std::option::Option::Some(ref v) = self.union {
|
||||
match v {
|
||||
&Message_oneof_union::register_peer(ref v) => {
|
||||
let len = v.compute_size();
|
||||
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
|
||||
},
|
||||
&Message_oneof_union::peek_peer(ref v) => {
|
||||
let len = v.compute_size();
|
||||
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
|
||||
},
|
||||
&Message_oneof_union::peek_peer_response(ref v) => {
|
||||
let len = v.compute_size();
|
||||
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
|
||||
},
|
||||
};
|
||||
}
|
||||
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
|
||||
self.cached_size.set(my_size);
|
||||
my_size
|
||||
}
|
||||
|
||||
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
|
||||
if let ::std::option::Option::Some(ref v) = self.union {
|
||||
match v {
|
||||
&Message_oneof_union::register_peer(ref v) => {
|
||||
os.write_tag(6, ::protobuf::wire_format::WireTypeLengthDelimited)?;
|
||||
os.write_raw_varint32(v.get_cached_size())?;
|
||||
v.write_to_with_cached_sizes(os)?;
|
||||
},
|
||||
&Message_oneof_union::peek_peer(ref v) => {
|
||||
os.write_tag(7, ::protobuf::wire_format::WireTypeLengthDelimited)?;
|
||||
os.write_raw_varint32(v.get_cached_size())?;
|
||||
v.write_to_with_cached_sizes(os)?;
|
||||
},
|
||||
&Message_oneof_union::peek_peer_response(ref v) => {
|
||||
os.write_tag(8, ::protobuf::wire_format::WireTypeLengthDelimited)?;
|
||||
os.write_raw_varint32(v.get_cached_size())?;
|
||||
v.write_to_with_cached_sizes(os)?;
|
||||
},
|
||||
};
|
||||
}
|
||||
os.write_unknown_fields(self.get_unknown_fields())?;
|
||||
::std::result::Result::Ok(())
|
||||
}
|
||||
|
||||
fn get_cached_size(&self) -> u32 {
|
||||
self.cached_size.get()
|
||||
}
|
||||
|
||||
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
|
||||
&self.unknown_fields
|
||||
}
|
||||
|
||||
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
|
||||
&mut self.unknown_fields
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn (::std::any::Any) {
|
||||
self as &dyn (::std::any::Any)
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
|
||||
self as &mut dyn (::std::any::Any)
|
||||
}
|
||||
fn into_any(self: Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
|
||||
self
|
||||
}
|
||||
|
||||
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
Self::descriptor_static()
|
||||
}
|
||||
|
||||
fn new() -> Message {
|
||||
Message::new()
|
||||
}
|
||||
|
||||
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
|
||||
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
|
||||
};
|
||||
unsafe {
|
||||
descriptor.get(|| {
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
fields.push(::protobuf::reflect::accessor::make_singular_message_accessor::<_, RegisterPeer>(
|
||||
"register_peer",
|
||||
Message::has_register_peer,
|
||||
Message::get_register_peer,
|
||||
));
|
||||
fields.push(::protobuf::reflect::accessor::make_singular_message_accessor::<_, PeekPeer>(
|
||||
"peek_peer",
|
||||
Message::has_peek_peer,
|
||||
Message::get_peek_peer,
|
||||
));
|
||||
fields.push(::protobuf::reflect::accessor::make_singular_message_accessor::<_, PeekPeerResponse>(
|
||||
"peek_peer_response",
|
||||
Message::has_peek_peer_response,
|
||||
Message::get_peek_peer_response,
|
||||
));
|
||||
::protobuf::reflect::MessageDescriptor::new::<Message>(
|
||||
"Message",
|
||||
fields,
|
||||
file_descriptor_proto()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_instance() -> &'static Message {
|
||||
static mut instance: ::protobuf::lazy::Lazy<Message> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const Message,
|
||||
};
|
||||
unsafe {
|
||||
instance.get(Message::new)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::Clear for Message {
|
||||
fn clear(&mut self) {
|
||||
self.union = ::std::option::Option::None;
|
||||
self.union = ::std::option::Option::None;
|
||||
self.union = ::std::option::Option::None;
|
||||
self.unknown_fields.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl ::std::fmt::Debug for Message {
|
||||
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
|
||||
::protobuf::text_format::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl ::protobuf::reflect::ProtobufValue for Message {
|
||||
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
|
||||
::protobuf::reflect::ProtobufValueRef::Message(self)
|
||||
}
|
||||
}
|
||||
|
||||
static file_descriptor_proto_data: &'static [u8] = b"\
|
||||
\n\rmessage.proto\x12\x03hbb\"$\n\x0cRegisterPeer\x12\x12\n\x08hbb_addr\
|
||||
\x18\x01\x20\x01(\tB\0:\0\"\x20\n\x08PeekPeer\x12\x12\n\x08hbb_addr\x18\
|
||||
\x01\x20\x01(\tB\0:\0\"+\n\x10PeekPeerResponse\x12\x15\n\x0bsocket_addr\
|
||||
\x18\x01\x20\x01(\x0cB\0:\0\"\x9f\x01\n\x07Message\x12,\n\rregister_peer\
|
||||
\x18\x06\x20\x01(\x0b2\x11.hbb.RegisterPeerH\0B\0\x12$\n\tpeek_peer\x18\
|
||||
\x07\x20\x01(\x0b2\r.hbb.PeekPeerH\0B\0\x125\n\x12peek_peer_response\x18\
|
||||
\x08\x20\x01(\x0b2\x15.hbb.PeekPeerResponseH\0B\0B\x07\n\x05union:\0B\0b\
|
||||
\x06proto3\
|
||||
";
|
||||
|
||||
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
|
||||
lock: ::protobuf::lazy::ONCE_INIT,
|
||||
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
|
||||
};
|
||||
|
||||
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
|
||||
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
|
||||
}
|
||||
|
||||
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
|
||||
unsafe {
|
||||
file_descriptor_proto_lazy.get(|| {
|
||||
parse_descriptor_proto()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,114 +1,644 @@
|
||||
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::{new_listener, FramedStream},
|
||||
tcp::{listen_any, FramedStream},
|
||||
timeout,
|
||||
tokio::{
|
||||
self,
|
||||
net::TcpListener,
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{Mutex, RwLock},
|
||||
time::{interval, Duration},
|
||||
},
|
||||
ResultType,
|
||||
};
|
||||
use sodiumoxide::crypto::sign;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
collections::{HashMap, HashSet},
|
||||
io::prelude::*,
|
||||
io::Error,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
type Usage = (usize, usize, usize, usize);
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref PEERS: Arc<Mutex<HashMap<String, FramedStream>>> = Arc::new(Mutex::new(HashMap::new()));
|
||||
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();
|
||||
}
|
||||
|
||||
pub const DEFAULT_PORT: &'static str = "21117";
|
||||
static mut DOWNGRADE_THRESHOLD: f64 = 0.66;
|
||||
static mut DOWNGRADE_START_CHECK: usize = 1_800_000; // in ms
|
||||
static mut LIMIT_SPEED: usize = 4 * 1024 * 1024; // in bit/s
|
||||
static mut TOTAL_BANDWIDTH: usize = 1024 * 1024 * 1024; // in bit/s
|
||||
static mut SINGLE_BANDWIDTH: usize = 16 * 1024 * 1024; // in bit/s
|
||||
const BLACKLIST_FILE: &str = "blacklist.txt";
|
||||
const BLOCKLIST_FILE: &str = "blocklist.txt";
|
||||
|
||||
#[tokio::main(basic_scheduler)]
|
||||
pub async fn start(port: &str, key: &str, stop: Arc<Mutex<bool>>) -> ResultType<()> {
|
||||
if !key.is_empty() {
|
||||
log::info!("Key: {}", key);
|
||||
}
|
||||
let addr = format!("0.0.0.0:{}", port);
|
||||
log::info!("Listening on tcp {}", addr);
|
||||
let mut listener = new_listener(addr, false).await?;
|
||||
loop {
|
||||
if *stop.lock().unwrap() {
|
||||
sleep(0.1).await;
|
||||
continue;
|
||||
#[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!("Start");
|
||||
io_loop(&mut listener, key, stop.clone()).await;
|
||||
}
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
async fn io_loop(listener: &mut TcpListener, key: &str, stop: Arc<Mutex<bool>>) {
|
||||
let mut timer = interval(Duration::from_millis(100));
|
||||
fn check_params() {
|
||||
let tmp = std::env::var("DOWNGRADE_THRESHOLD")
|
||||
.map(|x| x.parse::<f64>().unwrap_or(0.))
|
||||
.unwrap_or(0.);
|
||||
if tmp > 0. {
|
||||
unsafe {
|
||||
DOWNGRADE_THRESHOLD = tmp;
|
||||
}
|
||||
}
|
||||
unsafe { log::info!("DOWNGRADE_THRESHOLD: {}", DOWNGRADE_THRESHOLD) };
|
||||
let tmp = std::env::var("DOWNGRADE_START_CHECK")
|
||||
.map(|x| x.parse::<usize>().unwrap_or(0))
|
||||
.unwrap_or(0);
|
||||
if tmp > 0 {
|
||||
unsafe {
|
||||
DOWNGRADE_START_CHECK = tmp * 1000;
|
||||
}
|
||||
}
|
||||
unsafe { log::info!("DOWNGRADE_START_CHECK: {}s", DOWNGRADE_START_CHECK / 1000) };
|
||||
let tmp = std::env::var("LIMIT_SPEED")
|
||||
.map(|x| x.parse::<f64>().unwrap_or(0.))
|
||||
.unwrap_or(0.);
|
||||
if tmp > 0. {
|
||||
unsafe {
|
||||
LIMIT_SPEED = (tmp * 1024. * 1024.) as usize;
|
||||
}
|
||||
}
|
||||
unsafe { log::info!("LIMIT_SPEED: {}Mb/s", LIMIT_SPEED 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. {
|
||||
unsafe {
|
||||
TOTAL_BANDWIDTH = (tmp * 1024. * 1024.) as usize;
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
log::info!(
|
||||
"TOTAL_BANDWIDTH: {}Mb/s",
|
||||
TOTAL_BANDWIDTH 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. {
|
||||
unsafe {
|
||||
SINGLE_BANDWIDTH = (tmp * 1024. * 1024.) as usize;
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
log::info!(
|
||||
"SINGLE_BANDWIDTH: {}Mb/s",
|
||||
SINGLE_BANDWIDTH 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. {
|
||||
unsafe {
|
||||
DOWNGRADE_THRESHOLD = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
res = format!("{DOWNGRADE_THRESHOLD}\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("downgrade-start-check" | "t") => {
|
||||
if let Some(v) = fds.next() {
|
||||
if let Ok(v) = v.parse::<usize>() {
|
||||
if v > 0 {
|
||||
unsafe {
|
||||
DOWNGRADE_START_CHECK = v * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
res = format!("{}s\n", DOWNGRADE_START_CHECK / 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("limit-speed" | "ls") => {
|
||||
if let Some(v) = fds.next() {
|
||||
if let Ok(v) = v.parse::<f64>() {
|
||||
if v > 0. {
|
||||
unsafe {
|
||||
LIMIT_SPEED = (v * 1024. * 1024.) as _;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
res = format!("{}Mb/s\n", LIMIT_SPEED as f64 / 1024. / 1024.);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("total-bandwidth" | "tb") => {
|
||||
if let Some(v) = fds.next() {
|
||||
if let Ok(v) = v.parse::<f64>() {
|
||||
if v > 0. {
|
||||
unsafe {
|
||||
TOTAL_BANDWIDTH = (v * 1024. * 1024.) as _;
|
||||
limiter.set_speed_limit(TOTAL_BANDWIDTH as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
res = format!("{}Mb/s\n", TOTAL_BANDWIDTH as f64 / 1024. / 1024.);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("single-bandwidth" | "sb") => {
|
||||
if let Some(v) = fds.next() {
|
||||
if let Ok(v) = v.parse::<f64>() {
|
||||
if v > 0. {
|
||||
unsafe {
|
||||
SINGLE_BANDWIDTH = (v * 1024. * 1024.) as _;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
res = format!("{}Mb/s\n", SINGLE_BANDWIDTH 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(unsafe { TOTAL_BANDWIDTH as _ });
|
||||
loop {
|
||||
tokio::select! {
|
||||
Ok((stream, addr)) = listener.accept() => {
|
||||
let key = key.to_owned();
|
||||
tokio::spawn(async move {
|
||||
make_pair(FramedStream::from(stream), addr, &key).await.ok();
|
||||
});
|
||||
}
|
||||
_ = timer.tick() => {
|
||||
if *stop.lock().unwrap() {
|
||||
log::info!("Stopped");
|
||||
break;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn make_pair(stream: FramedStream, addr: SocketAddr, key: &str) -> ResultType<()> {
|
||||
let mut stream = stream;
|
||||
if let Some(Ok(bytes)) = stream.next_timeout(30_000).await {
|
||||
if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) {
|
||||
if let Some(rendezvous_message::Union::request_relay(rf)) = msg_in.union {
|
||||
if !key.is_empty() && rf.licence_key != key {
|
||||
return Ok(());
|
||||
}
|
||||
if !rf.uuid.is_empty() {
|
||||
let peer = PEERS.lock().unwrap().remove(&rf.uuid);
|
||||
if let Some(peer) = peer {
|
||||
log::info!("Forward request {} from {} got paired", rf.uuid, addr);
|
||||
return relay(stream, peer).await;
|
||||
} else {
|
||||
log::info!("New relay request {} from {}", rf.uuid, addr);
|
||||
PEERS.lock().unwrap().insert(rf.uuid.clone(), stream);
|
||||
sleep(30.).await;
|
||||
PEERS.lock().unwrap().remove(&rf.uuid);
|
||||
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 = addr.ip().to_string();
|
||||
if !ws && ip == "127.0.0.1" {
|
||||
let limiter = limiter.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut stream = stream;
|
||||
let mut buffer = [0; 64];
|
||||
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;
|
||||
}
|
||||
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,
|
||||
addr: SocketAddr,
|
||||
key: &str,
|
||||
limiter: Limiter,
|
||||
ws: bool,
|
||||
) -> ResultType<()> {
|
||||
if ws {
|
||||
make_pair_(
|
||||
tokio_tungstenite::accept_async(stream).await?,
|
||||
addr,
|
||||
key,
|
||||
limiter,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
make_pair_(FramedStream::from(stream, addr), addr, key, limiter).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn relay(stream: FramedStream, peer: FramedStream) -> ResultType<()> {
|
||||
let mut peer = peer;
|
||||
async fn make_pair_(stream: impl StreamTrait, addr: SocketAddr, key: &str, limiter: Limiter) {
|
||||
let mut stream = stream;
|
||||
peer.set_raw();
|
||||
stream.set_raw();
|
||||
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 {
|
||||
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 limiter = <Limiter>::new(unsafe { SINGLE_BANDWIDTH as _ });
|
||||
let blacklist_limiter = <Limiter>::new(unsafe { LIMIT_SPEED as _ });
|
||||
let downgrade_threshold =
|
||||
(unsafe { SINGLE_BANDWIDTH as f64 * DOWNGRADE_THRESHOLD } / 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.next() => {
|
||||
res = peer.recv() => {
|
||||
if let Some(Ok(bytes)) = res {
|
||||
stream.send_bytes(bytes.into()).await?;
|
||||
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.next() => {
|
||||
res = stream.recv() => {
|
||||
if let Some(Ok(bytes)) = res {
|
||||
peer.send_bytes(bytes.into()).await?;
|
||||
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 > unsafe { DOWNGRADE_START_CHECK }
|
||||
&& !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 diff suppressed because it is too large
Load Diff
@@ -1,101 +0,0 @@
|
||||
use hbb_common::{
|
||||
allow_err, log,
|
||||
tokio::{self, sync::mpsc},
|
||||
ResultType,
|
||||
};
|
||||
use rocksdb::DB;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Action {
|
||||
Insert((String, Vec<u8>)),
|
||||
Get((String, mpsc::Sender<Option<Vec<u8>>>)),
|
||||
_Close,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SledAsync {
|
||||
tx: Option<mpsc::UnboundedSender<Action>>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl SledAsync {
|
||||
pub fn new(path: &str, run: bool) -> ResultType<Self> {
|
||||
let mut res = Self {
|
||||
tx: None,
|
||||
path: path.to_owned(),
|
||||
};
|
||||
if run {
|
||||
res.run()?;
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn run(&mut self) -> ResultType<std::thread::JoinHandle<()>> {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Action>();
|
||||
self.tx = Some(tx);
|
||||
let db = DB::open_default(&self.path)?;
|
||||
Ok(std::thread::spawn(move || {
|
||||
Self::io_loop(db, rx);
|
||||
log::debug!("Exit SledAsync loop");
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::main(basic_scheduler)]
|
||||
async fn io_loop(db: DB, rx: mpsc::UnboundedReceiver<Action>) {
|
||||
let mut rx = rx;
|
||||
while let Some(x) = rx.recv().await {
|
||||
match x {
|
||||
Action::Insert((key, value)) => {
|
||||
allow_err!(db.put(&key, &value));
|
||||
}
|
||||
Action::Get((key, sender)) => {
|
||||
let mut sender = sender;
|
||||
allow_err!(
|
||||
sender
|
||||
.send(if let Ok(v) = db.get(key) { v } else { None })
|
||||
.await
|
||||
);
|
||||
}
|
||||
Action::_Close => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _close(self, j: std::thread::JoinHandle<()>) {
|
||||
if let Some(tx) = &self.tx {
|
||||
allow_err!(tx.send(Action::_Close));
|
||||
}
|
||||
allow_err!(j.join());
|
||||
}
|
||||
|
||||
pub async fn get(&mut self, key: String) -> Option<Vec<u8>> {
|
||||
if let Some(tx) = &self.tx {
|
||||
let (tx_once, mut rx) = mpsc::channel::<Option<Vec<u8>>>(1);
|
||||
allow_err!(tx.send(Action::Get((key, tx_once))));
|
||||
if let Some(v) = rx.recv().await {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn deserialize<'a, T: serde::Deserialize<'a>>(v: &'a Option<Vec<u8>>) -> Option<T> {
|
||||
if let Some(v) = v {
|
||||
if let Ok(v) = std::str::from_utf8(v) {
|
||||
if let Ok(v) = serde_json::from_str::<T>(&v) {
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn insert<T: serde::Serialize>(&mut self, key: String, v: T) {
|
||||
if let Some(tx) = &self.tx {
|
||||
if let Ok(v) = serde_json::to_vec(&v) {
|
||||
allow_err!(tx.send(Action::Insert((key, v))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
170
src/utils.rs
Normal file
170
src/utils.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use dns_lookup::{lookup_addr, lookup_host};
|
||||
use hbb_common::{bail, ResultType};
|
||||
use sodiumoxide::crypto::sign;
|
||||
use std::{
|
||||
env,
|
||||
net::{IpAddr, TcpStream},
|
||||
process, str,
|
||||
};
|
||||
|
||||
fn print_help() {
|
||||
println!(
|
||||
"Usage:
|
||||
rustdesk-util [command]\n
|
||||
Available Commands:
|
||||
genkeypair Generate a new keypair
|
||||
validatekeypair [public key] [secret key] Validate an existing keypair
|
||||
doctor [rustdesk-server] Check for server connection problems"
|
||||
);
|
||||
process::exit(0x0001);
|
||||
}
|
||||
|
||||
fn error_then_help(msg: &str) {
|
||||
println!("ERROR: {msg}\n");
|
||||
print_help();
|
||||
}
|
||||
|
||||
fn gen_keypair() {
|
||||
let (pk, sk) = sign::gen_keypair();
|
||||
let public_key = base64::encode(pk);
|
||||
let secret_key = base64::encode(sk);
|
||||
println!("Public Key: {public_key}");
|
||||
println!("Secret Key: {secret_key}");
|
||||
}
|
||||
|
||||
fn validate_keypair(pk: &str, sk: &str) -> ResultType<()> {
|
||||
let sk1 = base64::decode(sk);
|
||||
if sk1.is_err() {
|
||||
bail!("Invalid secret key");
|
||||
}
|
||||
let sk1 = sk1.unwrap();
|
||||
|
||||
let secret_key = sign::SecretKey::from_slice(sk1.as_slice());
|
||||
if secret_key.is_none() {
|
||||
bail!("Invalid Secret key");
|
||||
}
|
||||
let secret_key = secret_key.unwrap();
|
||||
|
||||
let pk1 = base64::decode(pk);
|
||||
if pk1.is_err() {
|
||||
bail!("Invalid public key");
|
||||
}
|
||||
let pk1 = pk1.unwrap();
|
||||
|
||||
let public_key = sign::PublicKey::from_slice(pk1.as_slice());
|
||||
if public_key.is_none() {
|
||||
bail!("Invalid Public key");
|
||||
}
|
||||
let public_key = public_key.unwrap();
|
||||
|
||||
let random_data_to_test = b"This is meh.";
|
||||
let signed_data = sign::sign(random_data_to_test, &secret_key);
|
||||
let verified_data = sign::verify(&signed_data, &public_key);
|
||||
if verified_data.is_err() {
|
||||
bail!("Key pair is INVALID");
|
||||
}
|
||||
let verified_data = verified_data.unwrap();
|
||||
|
||||
if random_data_to_test != &verified_data[..] {
|
||||
bail!("Key pair is INVALID");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn doctor_tcp(address: std::net::IpAddr, port: &str, desc: &str) {
|
||||
let start = std::time::Instant::now();
|
||||
let conn = format!("{address}:{port}");
|
||||
if let Ok(_stream) = TcpStream::connect(conn.as_str()) {
|
||||
let elapsed = std::time::Instant::now().duration_since(start);
|
||||
println!(
|
||||
"TCP Port {} ({}): OK in {} ms",
|
||||
port,
|
||||
desc,
|
||||
elapsed.as_millis()
|
||||
);
|
||||
} else {
|
||||
println!("TCP Port {port} ({desc}): ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
fn doctor_ip(server_ip_address: std::net::IpAddr, server_address: Option<&str>) {
|
||||
println!("\nChecking IP address: {server_ip_address}");
|
||||
println!("Is IPV4: {}", server_ip_address.is_ipv4());
|
||||
println!("Is IPV6: {}", server_ip_address.is_ipv6());
|
||||
|
||||
// reverse dns lookup
|
||||
// TODO: (check) doesn't seem to do reverse lookup on OSX...
|
||||
let reverse = lookup_addr(&server_ip_address).unwrap();
|
||||
if let Some(server_address) = server_address {
|
||||
if reverse == server_address {
|
||||
println!("Reverse DNS lookup: '{reverse}' MATCHES server address");
|
||||
} else {
|
||||
println!(
|
||||
"Reverse DNS lookup: '{reverse}' DOESN'T MATCH server address '{server_address}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: ICMP ping?
|
||||
|
||||
// port check TCP (UDP is hard to check)
|
||||
doctor_tcp(server_ip_address, "21114", "API");
|
||||
doctor_tcp(server_ip_address, "21115", "hbbs extra port for nat test");
|
||||
doctor_tcp(server_ip_address, "21116", "hbbs");
|
||||
doctor_tcp(server_ip_address, "21117", "hbbr tcp");
|
||||
doctor_tcp(server_ip_address, "21118", "hbbs websocket");
|
||||
doctor_tcp(server_ip_address, "21119", "hbbr websocket");
|
||||
|
||||
// TODO: key check
|
||||
}
|
||||
|
||||
fn doctor(server_address_unclean: &str) {
|
||||
let server_address3 = server_address_unclean.trim();
|
||||
let server_address2 = server_address3.to_lowercase();
|
||||
let server_address = server_address2.as_str();
|
||||
println!("Checking server: {server_address}\n");
|
||||
if let Ok(server_ipaddr) = server_address.parse::<IpAddr>() {
|
||||
// user requested an ip address
|
||||
doctor_ip(server_ipaddr, None);
|
||||
} else {
|
||||
// the passed string is not an ip address
|
||||
let ips: Vec<std::net::IpAddr> = lookup_host(server_address).unwrap();
|
||||
println!("Found {} IP addresses: ", ips.len());
|
||||
|
||||
ips.iter().for_each(|ip| println!(" - {ip}"));
|
||||
|
||||
ips.iter()
|
||||
.for_each(|ip| doctor_ip(*ip, Some(server_address)));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<_> = env::args().collect();
|
||||
if args.len() <= 1 {
|
||||
print_help();
|
||||
}
|
||||
|
||||
let command = args[1].to_lowercase();
|
||||
match command.as_str() {
|
||||
"genkeypair" => gen_keypair(),
|
||||
"validatekeypair" => {
|
||||
if args.len() <= 3 {
|
||||
error_then_help("You must supply both the public and the secret key");
|
||||
}
|
||||
let res = validate_keypair(args[2].as_str(), args[3].as_str());
|
||||
if let Err(e) = res {
|
||||
println!("{e}");
|
||||
process::exit(0x0001);
|
||||
}
|
||||
println!("Key pair is VALID");
|
||||
}
|
||||
"doctor" => {
|
||||
if args.len() <= 2 {
|
||||
error_then_help("You must supply the rustdesk-server address");
|
||||
}
|
||||
doctor(args[2].as_str());
|
||||
}
|
||||
_ => print_help(),
|
||||
}
|
||||
}
|
||||
20
systemd/rustdesk-hbbr.service
Normal file
20
systemd/rustdesk-hbbr.service
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
[Unit]
|
||||
Description=Rustdesk Relay Server
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
LimitNOFILE=1000000
|
||||
ExecStart=/usr/bin/hbbr
|
||||
WorkingDirectory=/var/lib/rustdesk-server/
|
||||
User=
|
||||
Group=
|
||||
Restart=always
|
||||
StandardOutput=append:/var/log/rustdesk/rustdesk-hbbr.log
|
||||
StandardError=append:/var/log/rustdesk/rustdesk-hbbr.error
|
||||
# Restart service after 10 seconds if node service crashes
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
20
systemd/rustdesk-hbbs.service
Normal file
20
systemd/rustdesk-hbbs.service
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
[Unit]
|
||||
Description=Rustdesk Signal Server
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
LimitNOFILE=1000000
|
||||
ExecStart=/usr/bin/hbbs
|
||||
WorkingDirectory=/var/lib/rustdesk-server/
|
||||
User=
|
||||
Group=
|
||||
Restart=always
|
||||
StandardOutput=append:/var/log/rustdesk/rustdesk-hbbs.log
|
||||
StandardError=append:/var/log/rustdesk/rustdesk-hbbs.error
|
||||
# Restart service after 10 seconds if node service crashes
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
4
ui/.gitignore
vendored
Normal file
4
ui/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user