Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
071d9b1eff |
Generated
+14
-15
@@ -3737,7 +3737,7 @@ dependencies = [
|
||||
"url",
|
||||
"users",
|
||||
"uuid",
|
||||
"webpki-roots 1.0.10",
|
||||
"webpki-roots 1.0.9",
|
||||
"webrtc",
|
||||
"whoami",
|
||||
"x11 2.21.0",
|
||||
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
|
||||
|
||||
[[package]]
|
||||
name = "hwcodec"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#febec27e1b40bb9fbbae02e9c59b71ac824b9fe1"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
|
||||
dependencies = [
|
||||
"bindgen 0.59.2",
|
||||
"cc",
|
||||
@@ -3935,7 +3935,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots 1.0.10",
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6930,7 +6930,7 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots 1.0.10",
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7296,12 +7296,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7333,9 +7332,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.16"
|
||||
version = "0.103.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
@@ -9540,9 +9539,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.10"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
|
||||
checksum = "05d651ec480de84b762e7be71e6efa7461699c19d9e2c272c8d93455f567786e"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
@@ -9553,14 +9552,14 @@ version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.10",
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.10"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
|
||||
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<a href="#how-to-build-with-docker">Docker</a> •
|
||||
<a href="#file-structure">Structure</a> •
|
||||
<a href="#screenshots">Screenshots</a><br>
|
||||
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTPT.md">Português (Portugal)</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
|
||||
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
|
||||
<b>We need your help to translate this README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> and <a href="https://github.com/rustdesk/doc.rustdesk.com">RustDesk Doc</a> to your native language</b>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -2,12 +2,7 @@
|
||||
fn build_windows() {
|
||||
let file = "src/platform/windows.cc";
|
||||
let file2 = "src/platform/windows_delete_test_cert.cc";
|
||||
let mut build = cc::Build::new();
|
||||
if !cfg!(feature = "flutter") {
|
||||
build.cpp(true).std("c++17").define("RUSTDESK_SCITER", None);
|
||||
println!("cargo:rerun-if-changed=flutter/windows/runner/service_control.h");
|
||||
}
|
||||
build.file(file).file(file2).compile("windows");
|
||||
cc::Build::new().file(file).file(file2).compile("windows");
|
||||
println!("cargo:rustc-link-lib=WtsApi32");
|
||||
println!("cargo:rerun-if-changed={}", file);
|
||||
println!("cargo:rerun-if-changed={}", file2);
|
||||
|
||||
+1
-8
@@ -9,10 +9,6 @@
|
||||
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
|
||||
</p>
|
||||
|
||||
> [!Caution]
|
||||
> **Peringatan Penyalahgunaan:** <br>
|
||||
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
|
||||
|
||||
Mari mengobrol bersama kami: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
@@ -34,9 +30,6 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
|
||||
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
|
||||
alt="Get it on F-Droid"
|
||||
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
|
||||
[<img src="https://flathub.org/api/badge?svg&locale=en"
|
||||
alt="Get it on Flathub"
|
||||
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
|
||||
|
||||
## Dependensi
|
||||
|
||||
@@ -161,7 +154,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
|
||||
|
||||
## Snapshots
|
||||
|
||||

|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - O seu ambiente de trabalho remoto"><br>
|
||||
<a href="#compilar">Compilar</a> •
|
||||
<a href="#como-compilar-com-o-docker">Docker</a> •
|
||||
<a href="#estrutura-de-ficheiros">Estrutura</a> •
|
||||
<a href="#capturas-de-ecrã">Capturas de Ecrã</a><br>
|
||||
[<a href="../README.md">Inglês</a>] | [<a href="README-UA.md">Ucraniano</a>] | [<a href="README-CS.md">Checo</a>] | [<a href="README-ZH.md">Chinês</a>] | [<a href="README-HU.md">Húngaro</a>] | [<a href="README-ES.md">Espanhol</a>] | [<a href="README-FA.md">Persa</a>] | [<a href="README-FR.md">Francês</a>] | [<a href="README-DE.md">Alemão</a>] | [<a href="README-PL.md">Polaco</a>] | [<a href="README-ID.md">Indonésio</a>] | [<a href="README-FI.md">Finlandês</a>] | [<a href="README-ML.md">Malaiala</a>] | [<a href="README-JP.md">Japonês</a>] | [<a href="README-NL.md">Holandês</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Russo</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">Coreano</a>] | [<a href="README-AR.md">Árabe</a>] | [<a href="README-VN.md">Vietnamita</a>] | [<a href="README-DA.md">Dinamarquês</a>] | [<a href="README-GR.md">Grego</a>] | [<a href="README-TR.md">Turco</a>] | [<a href="README-NO.md">Norueguês</a>] | [<a href="README-RO.md">Romeno</a>]<br>
|
||||
<b>Precisamos da sua ajuda para traduzir este README, a <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">Interface do RustDesk</a> e a <a href="https://github.com/rustdesk/doc.rustdesk.com">Documentação do RustDesk</a> para o seu idioma nativo</b>
|
||||
</p>
|
||||
|
||||
> [!Caution]
|
||||
> **Aviso de Isenção de Responsabilidade por Uso Indevido:** <br>
|
||||
> Os programadores do RustDesk não toleram ou apoiam qualquer uso antiético ou ilegal deste software. O uso indevido, como acesso não autorizado, controlo ou invasão de privacidade, é estritamente contrário às nossas diretrizes. Os autores não se responsabilizam por qualquer uso indevido da aplicação.
|
||||
|
||||
|
||||
Converse connosco: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
|
||||
Mais uma solução de ambiente de trabalho remoto, escrita em Rust. Funciona imediatamente, sem necessidade de configuração. Tem controlo total dos seus dados, sem preocupações com a segurança. Pode usar o nosso servidor de ligação/retransmissão (rendezvous/relay), [configurar o seu próprio](https://rustdesk.com/server) ou [escrever o seu próprio servidor de ligação/retransmissão](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
|
||||

|
||||
|
||||
O RustDesk agradece as contribuições de todos. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para obter ajuda para começar.
|
||||
|
||||
[**Perguntas Frequentes (FAQ)**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
|
||||
|
||||
[**DOWNLOAD DOS BINÁRIOS**](https://github.com/rustdesk/rustdesk/releases)
|
||||
|
||||
[**VERSÕES NIGHTLY (EM DESENVOLVIMENTO)**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
|
||||
|
||||
[<img src="https://f-droid.org/badge/get-it-on.png"
|
||||
alt="Transfira no F-Droid"
|
||||
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
|
||||
[<img src="https://flathub.org/api/badge?svg&locale=en"
|
||||
alt="Transfira no Flathub"
|
||||
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
|
||||
|
||||
## Dependências
|
||||
|
||||
As versões para ambiente de trabalho usam Flutter ou Sciter (descontinuado) para a interface gráfica (GUI). Este tutorial é apenas para o Sciter, por ser mais fácil e acessível para começar. Consulte o nosso [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) para instruções de compilação da versão Flutter.
|
||||
|
||||
Por favor transfira a biblioteca dinâmica do Sciter por conta própria.
|
||||
|
||||
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
|
||||
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
|
||||
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
|
||||
|
||||
## Passos básicos para compilar
|
||||
|
||||
- Prepare o seu ambiente de desenvolvimento Rust e o ambiente de compilação C++
|
||||
|
||||
- Instale o [vcpkg](https://github.com/microsoft/vcpkg) e configure a variável de ambiente `VCPKG_ROOT` corretamente
|
||||
|
||||
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static`
|
||||
- Linux/macOS: `vcpkg install libvpx libyuv opus aom`
|
||||
|
||||
- Execute `cargo run`
|
||||
|
||||
## [Compilar](https://rustdesk.com/docs/en/dev/build/)
|
||||
|
||||
## Como Compilar no Linux
|
||||
|
||||
### Ubuntu 18 (Debian 10)
|
||||
|
||||
```sh
|
||||
sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
|
||||
```
|
||||
|
||||
### openSUSE Tumbleweed
|
||||
|
||||
```sh
|
||||
sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel
|
||||
```
|
||||
|
||||
### Fedora 28 (CentOS 8)
|
||||
|
||||
```sh
|
||||
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel
|
||||
```
|
||||
|
||||
### Arch (Manjaro)
|
||||
|
||||
```sh
|
||||
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire
|
||||
```
|
||||
|
||||
### Instalar o vcpkg
|
||||
|
||||
```sh
|
||||
git clone https://github.com/microsoft/vcpkg
|
||||
cd vcpkg
|
||||
git checkout 2023.04.15
|
||||
cd ..
|
||||
vcpkg/bootstrap-vcpkg.sh
|
||||
export VCPKG_ROOT=$HOME/vcpkg
|
||||
vcpkg/vcpkg install libvpx libyuv opus aom
|
||||
```
|
||||
|
||||
### Corrigir o libvpx (Para Fedora)
|
||||
|
||||
```sh
|
||||
cd vcpkg/buildtrees/libvpx/src
|
||||
cd *
|
||||
./configure
|
||||
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
|
||||
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
|
||||
make
|
||||
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
|
||||
cd
|
||||
```
|
||||
|
||||
### Compilar
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
source $HOME/.cargo/env
|
||||
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
|
||||
cd rustdesk
|
||||
mkdir -p target/debug
|
||||
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
|
||||
mv libsciter-gtk.so target/debug
|
||||
VCPKG_ROOT=$HOME/vcpkg cargo run
|
||||
```
|
||||
|
||||
## Como compilar com o Docker
|
||||
|
||||
Comece por clonar o repositório e construir o contentor Docker:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/rustdesk/rustdesk
|
||||
cd rustdesk
|
||||
git submodule update --init --recursive
|
||||
docker build -t "rustdesk-builder" .
|
||||
```
|
||||
|
||||
Depois, cada vez que precisar de compilar a aplicação, execute o seguinte comando:
|
||||
|
||||
```sh
|
||||
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
|
||||
```
|
||||
|
||||
Note que a primeira compilação pode demorar mais até que as dependências sejam armazenadas em cache, as compilações subsequentes serão mais rápidas. Além disso, se precisar especificar argumentos diferentes para o comando de compilação, poderá fazê-lo no final do comando na posição `<ARGUMENTOS-OPCIONAIS>`. Por exemplo, se quiser compilar uma versão de lançamento (release) otimizada, executaria o comando acima seguido de `--release`. O executável resultante estará disponível na pasta `target` do seu sistema e pode ser executado com:
|
||||
|
||||
```sh
|
||||
target/debug/rustdesk
|
||||
```
|
||||
|
||||
Ou, se estiver a correr o executável de lançamento:
|
||||
|
||||
```sh
|
||||
target/release/rustdesk
|
||||
```
|
||||
|
||||
Certifique-se de que executa estes comandos a partir da raiz do repositório do RustDesk, caso contrário a aplicação poderá não encontrar os recursos necessários. Note também que outros subcomandos do cargo, como `install` ou `run`, não são suportados atualmente por este método, pois instalariam ou executariam o programa dentro do contentor em vez de o fazerem no host.
|
||||
|
||||
## Estrutura de Ficheiros
|
||||
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: codec de vídeo, configuração, wrapper TCP/UDP e algumas outras funções utilitárias partilhadas com o servidor
|
||||
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, funções fs para transferência de ficheiros, código relacionado com o teclado e com a plataforma utilizado exclusivamente por esta aplicação
|
||||
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de ecrã
|
||||
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: controlo de teclado/rato específico da plataforma.
|
||||
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: implementação de copiar e colar ficheiros para Windows, Linux e macOS.
|
||||
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: interface Sciter obsoleta (descontinuada).
|
||||
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: serviços de áudio, área de transferência, entrada e vídeo, e ligações de rede
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: inicia uma ligação entre pares
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunica com o [rustdesk-server](https://github.com/rustdesk/rustdesk-server), aguarda por uma ligação direta remota (TCP hole punching) ou uma ligação retransmitida
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico da plataforma
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: código Flutter para ambiente de trabalho e dispositivos móveis
|
||||
|
||||
## Capturas de Ecrã
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
@@ -50,15 +50,6 @@ const val WHEEL_BUTTON_UP = 34
|
||||
const val WHEEL_DOWN = 523331
|
||||
const val WHEEL_UP = 963
|
||||
|
||||
// src/common.rs MOUSE_TYPE_WHEEL: the controller sends a wheel tick as a
|
||||
// MouseEvent with these type bits and the scroll delta in y (y < 0 = down).
|
||||
const val MOUSE_TYPE_WHEEL = 3
|
||||
|
||||
// Wheel-tick travel for MOUSE_TYPE_WHEEL events. Three quarters of the legacy
|
||||
// WHEEL_STEP; tuned on real devices during review (the full 120px felt too
|
||||
// far per tick).
|
||||
const val MOUSE_WHEEL_STEP = 90
|
||||
|
||||
const val TOUCH_SCALE_START = 1
|
||||
const val TOUCH_SCALE = 2
|
||||
const val TOUCH_SCALE_END = 3
|
||||
@@ -111,12 +102,6 @@ class InputService : AccessibilityService() {
|
||||
|
||||
private val volumeController: VolumeController by lazy { VolumeController(applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager) }
|
||||
|
||||
/**
|
||||
* Handles a remote mouse event on the gesture path. [mask] is the
|
||||
* button/phase mask of the mouse protocol ([MOUSE_TYPE_WHEEL] ticks carry
|
||||
* the scroll delta in [_y] instead of a position), x/y the screen-space
|
||||
* position. Requires API 24 for the gesture APIs.
|
||||
*/
|
||||
@RequiresApi(Build.VERSION_CODES.N)
|
||||
fun onMouseInput(mask: Int, _x: Int, _y: Int) {
|
||||
val x = max(0, _x)
|
||||
@@ -199,38 +184,6 @@ class InputService : AccessibilityService() {
|
||||
return
|
||||
}
|
||||
|
||||
// The controller sends a wheel tick as a MouseEvent with the type bits
|
||||
// MOUSE_TYPE_WHEEL (src/common.rs) and the scroll delta in _y
|
||||
// (y < 0 = wheel down); the WHEEL_DOWN/WHEEL_UP masks below are legacy
|
||||
// values that current controllers never send. Gated to API 24+ like
|
||||
// the rest of the gesture path - below that, legacy devices take the
|
||||
// Shizuku backend or a no-op, not this class.
|
||||
if (mask == MOUSE_TYPE_WHEEL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
// A horizontal tick (the controller sends y = 0 when the
|
||||
// horizontal delta dominates) or a delta truncated to zero is not
|
||||
// a vertical swipe.
|
||||
if (_y == 0) {
|
||||
return
|
||||
}
|
||||
if (mouseY < MOUSE_WHEEL_STEP) {
|
||||
return
|
||||
}
|
||||
val path = Path()
|
||||
path.moveTo(mouseX.toFloat(), mouseY.toFloat())
|
||||
val deltaY = if (_y < 0) -MOUSE_WHEEL_STEP else MOUSE_WHEEL_STEP
|
||||
path.lineTo(mouseX.toFloat(), (mouseY + deltaY).toFloat())
|
||||
val stroke = GestureDescription.StrokeDescription(
|
||||
path,
|
||||
0,
|
||||
WHEEL_DURATION
|
||||
)
|
||||
val builder = GestureDescription.Builder()
|
||||
builder.addStroke(stroke)
|
||||
wheelActionsQueue.offer(builder.build())
|
||||
consumeWheelActions()
|
||||
return
|
||||
}
|
||||
|
||||
if (mask == WHEEL_DOWN) {
|
||||
if (mouseY < WHEEL_STEP) {
|
||||
return
|
||||
|
||||
@@ -346,7 +346,7 @@ prebuild)
|
||||
pushd flutter
|
||||
|
||||
flutter clean
|
||||
flutter packages pub get --enforce-lockfile
|
||||
flutter packages pub get
|
||||
|
||||
popd # flutter
|
||||
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
|
||||
String _resolveApiServer({required String api, required String custom}) {
|
||||
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
|
||||
final response = jsonDecode(bind.mainGetCommonSync(key: key));
|
||||
if (response['error'] != null) {
|
||||
throw FormatException('Failed to resolve API server: ${response['error']}');
|
||||
}
|
||||
return response['url'] as String;
|
||||
}
|
||||
|
||||
bool shouldWarnApiServer(String? apiServer) {
|
||||
final uri = Uri.tryParse(apiServer?.trim() ?? '');
|
||||
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
|
||||
return false;
|
||||
}
|
||||
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
|
||||
}
|
||||
|
||||
class ApiServerWarning extends StatelessWidget {
|
||||
final TextEditingController controller;
|
||||
final TextEditingController idController;
|
||||
final String message;
|
||||
final String emptyMessage;
|
||||
final String Function({required String api, required String custom})
|
||||
resolveApiServer;
|
||||
|
||||
const ApiServerWarning({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.idController,
|
||||
required this.message,
|
||||
required this.emptyMessage,
|
||||
this.resolveApiServer = _resolveApiServer,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([controller, idController]),
|
||||
builder: (context, child) {
|
||||
final apiServer = controller.text;
|
||||
final idServer = idController.text;
|
||||
final String effectiveApiServer;
|
||||
try {
|
||||
effectiveApiServer =
|
||||
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
|
||||
} catch (error, stack) {
|
||||
FlutterError.reportError(FlutterErrorDetails(
|
||||
exception: error,
|
||||
stack: stack,
|
||||
context: ErrorDescription('while resolving the API server warning'),
|
||||
));
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (!shouldWarnApiServer(effectiveApiServer)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Text(
|
||||
controller.text.trim().isEmpty ? emptyMessage : message,
|
||||
style: TextStyle(color: Colors.orange.shade700),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -497,12 +497,7 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
},
|
||||
onExit: (evt) =>
|
||||
widget._mouseFocusScope.value = MouseFocusScope.none,
|
||||
child: Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: _onFileListKeyEvent,
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
),
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
))
|
||||
],
|
||||
),
|
||||
@@ -1140,7 +1135,6 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
|
||||
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
|
||||
onTap() {
|
||||
_keyboardNode.requestFocus();
|
||||
final items = selectedItems;
|
||||
// handle double click
|
||||
if (_checkDoubleClick(entry)) {
|
||||
@@ -1369,102 +1363,6 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
debugPrint("focused on ${searchResult.first.name}");
|
||||
}
|
||||
|
||||
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
|
||||
// A focused child such as a sort header keeps its default keys, e.g.
|
||||
// Enter to sort.
|
||||
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
|
||||
for (final binding in _fileListKeyBindings().entries) {
|
||||
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
|
||||
binding.value();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
|
||||
int all() => controller.directory.value.entries.length;
|
||||
return {
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
|
||||
_moveSelectionByKey(-1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
|
||||
_moveSelectionByKey(1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
|
||||
_moveSelectionByKey(-1, true),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
|
||||
_moveSelectionByKey(1, true),
|
||||
// Unhandled, they would move keyboard focus to the other pane.
|
||||
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), false),
|
||||
const SingleActivator(LogicalKeyboardKey.home): () =>
|
||||
_moveSelectionByKey(-all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.end): () =>
|
||||
_moveSelectionByKey(all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), true),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), true),
|
||||
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
|
||||
_moveSelectionByKey(-all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
|
||||
_moveSelectionByKey(all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter):
|
||||
_openSelectedDirectory,
|
||||
};
|
||||
}
|
||||
|
||||
void _openSelectedDirectory() {
|
||||
final items = selectedItems.items;
|
||||
if (items.length != 1 || items.first.isFile) return;
|
||||
controller.openDirectory(items.first.path);
|
||||
selectedItems.clear();
|
||||
}
|
||||
|
||||
List<Entry> _filteredEntries() {
|
||||
final entries = controller.directory.value.entries;
|
||||
return _searchText.isNotEmpty
|
||||
? entries.where((element) {
|
||||
return element.name.contains(_searchText.value);
|
||||
}).toList(growable: false)
|
||||
: entries;
|
||||
}
|
||||
|
||||
int _pageDelta(bool down) {
|
||||
final entries = _filteredEntries();
|
||||
final items = selectedItems.items;
|
||||
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
|
||||
final position = _fileListScrollController.position;
|
||||
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
|
||||
final last = ((position.pixels + position.viewportDimension) /
|
||||
kDesktopFileTransferRowHeight)
|
||||
.floor() -
|
||||
1;
|
||||
return pageDelta(
|
||||
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
|
||||
}
|
||||
|
||||
void _moveSelectionByKey(int delta, bool extend) {
|
||||
final filteredEntries = _filteredEntries();
|
||||
final selection =
|
||||
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
|
||||
if (selection.isEmpty) return;
|
||||
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
|
||||
final position = _fileListScrollController.position;
|
||||
final top =
|
||||
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
|
||||
final bottom = top + kDesktopFileTransferRowHeight;
|
||||
if (top < position.pixels) {
|
||||
_fileListScrollController.jumpTo(top);
|
||||
} else if (bottom > position.pixels + position.viewportDimension) {
|
||||
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
|
||||
}
|
||||
}
|
||||
|
||||
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
|
||||
Entry entry, bool isLocal) {
|
||||
final isCtrlDown = RawKeyboard.instance.keysPressed
|
||||
@@ -1819,36 +1717,6 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
// }
|
||||
}
|
||||
|
||||
/// Selection after a navigation key moves it by [delta] rows. A shift range is
|
||||
/// returned ordered from its anchor to the moved end, so the first and last
|
||||
/// items of [selected] stand for those two ends on the next press without
|
||||
/// separate state.
|
||||
@visibleForTesting
|
||||
List<Entry> navigateSelection(
|
||||
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
|
||||
if (entries.isEmpty) return [];
|
||||
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
|
||||
// With nothing selected, moving down starts above the first row and moving
|
||||
// up below the last one, as the Sciter grid did.
|
||||
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
|
||||
final next = (lead + delta).clamp(0, entries.length - 1);
|
||||
if (!extend || current < 0) return [entries[next]];
|
||||
final first = entries.indexOf(selected.first);
|
||||
final anchor = first < 0 ? current : first;
|
||||
final step = next < anchor ? -1 : 1;
|
||||
return [for (var i = anchor; i != next + step; i += step) entries[i]];
|
||||
}
|
||||
|
||||
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
|
||||
/// are fully visible: to that edge first, then a page further, as list views
|
||||
/// do.
|
||||
@visibleForTesting
|
||||
int pageDelta(int lead, int first, int last, bool down) {
|
||||
final page = max(1, last - first);
|
||||
if (down) return lead < last ? last - lead : page;
|
||||
return lead > first ? first - lead : -page;
|
||||
}
|
||||
|
||||
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
|
||||
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
|
||||
return Row(children: [
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class ListSearchActionListener extends StatelessWidget {
|
||||
final FocusNode node;
|
||||
@@ -23,7 +22,7 @@ class ListSearchActionListener extends StatelessWidget {
|
||||
autofocus: true,
|
||||
onKeyEvent: (kv) {
|
||||
final ch = kv.character;
|
||||
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
|
||||
if (ch == null) {
|
||||
return;
|
||||
}
|
||||
final action = buffer.input(ch);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
|
||||
import 'package:flutter_hbb/common/widgets/toolbar.dart';
|
||||
import 'package:get/get.dart';
|
||||
@@ -70,8 +69,6 @@ void showServerSettingsWithValue(
|
||||
ServerConfig serverConfig,
|
||||
OverlayDialogManager dialogManager,
|
||||
void Function(VoidCallback)? upSetState) async {
|
||||
const labelWidth = 120.0;
|
||||
const labelSpacing = 8.0;
|
||||
var isInProgress = false;
|
||||
final idCtrl = TextEditingController(text: serverConfig.idServer);
|
||||
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
|
||||
@@ -115,10 +112,10 @@ void showServerSettingsWithValue(
|
||||
return Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: labelWidth,
|
||||
width: 120,
|
||||
child: Text(label),
|
||||
),
|
||||
SizedBox(width: labelSpacing),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: serverSettingsTextFormField(
|
||||
label: label,
|
||||
@@ -178,17 +175,6 @@ void showServerSettingsWithValue(
|
||||
return null;
|
||||
},
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsetsDirectional.only(
|
||||
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
|
||||
),
|
||||
child: ApiServerWarning(
|
||||
controller: apiCtrl,
|
||||
idController: idCtrl,
|
||||
message: translate('api_server_connection_tip'),
|
||||
emptyMessage: translate('api_server_empty_tip'),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
buildField('Key', keyCtrl, ''),
|
||||
if (isInProgress)
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/common/widgets/dialog.dart';
|
||||
import 'package:flutter_hbb/utils/download_paths.dart';
|
||||
import 'package:flutter_hbb/utils/event_loop.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
@@ -628,17 +627,6 @@ class FileController {
|
||||
final transferJobIds = <int>[];
|
||||
for (var from in items.items) {
|
||||
final jobID = jobController.addTransferJob(from, isRemoteToLocal);
|
||||
// Keep this check before PathUtil.join: Rust does not receive the selected
|
||||
// root separately, and Web transfers bypass Rust validation.
|
||||
if (isRemoteToLocal &&
|
||||
!DownloadPaths.validName(from.name, windows: isWindows)) {
|
||||
jobController.jobError({
|
||||
'id': '$jobID',
|
||||
'file_num': '0',
|
||||
'err': 'Invalid file name: ${from.name}',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
transferJobs.add((from, jobID));
|
||||
transferJobIds.add(jobID);
|
||||
}
|
||||
@@ -663,15 +651,6 @@ class FileController {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRemoteToLocal) {
|
||||
for (final (entry, jobID) in transferJobs) {
|
||||
if (entry.isDirectory) {
|
||||
await _downloadEmptyDirectories(entry, jobID, otherSideData);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Entry> entrys = items.items.toList();
|
||||
var isRemote = isLocal == true ? true : false;
|
||||
|
||||
@@ -704,35 +683,6 @@ class FileController {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _downloadEmptyDirectories(
|
||||
Entry entry, int jobID, DirectoryData destination) async {
|
||||
try {
|
||||
final emptyDirs = await fileFetcher.readEmptyDirs(
|
||||
entry.path, false, destination.options.showHidden);
|
||||
final localRoot = PathUtil.join(destination.directory.path, entry.name,
|
||||
destination.options.isWindows);
|
||||
final paths = emptyDirs
|
||||
.map((dir) => DownloadPaths.mapDirectory(
|
||||
entry.path, dir.path, localRoot,
|
||||
remoteWindows: options.value.isWindows,
|
||||
localWindows: destination.options.isWindows))
|
||||
.toList();
|
||||
for (final path in paths) {
|
||||
await DownloadPaths.ensureNoLinks(destination.directory.path, path);
|
||||
}
|
||||
for (final path in paths) {
|
||||
await createDirWithRemote(path, false);
|
||||
}
|
||||
} on FormatException catch (err) {
|
||||
await bind.sessionCancelJob(sessionId: sessionId, actId: jobID);
|
||||
jobController.jobError({
|
||||
'id': '$jobID',
|
||||
'file_num': '0',
|
||||
'err': err.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
bool _removeCheckboxRemember = false;
|
||||
|
||||
Future<void> removeAction(SelectedItems items) async {
|
||||
@@ -1170,11 +1120,6 @@ class JobController {
|
||||
return true;
|
||||
}
|
||||
final job = jobTable[jobIndex];
|
||||
if (job.type == JobType.transfer &&
|
||||
job.isRemoteToLocal &&
|
||||
job.state == JobState.error) {
|
||||
return true;
|
||||
}
|
||||
job.recvJobRes = true;
|
||||
if (job.type == JobType.deleteFile) {
|
||||
job.state = JobState.done;
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
class DownloadPaths {
|
||||
static Future<void> ensureNoLinks(String root, String destination) async {
|
||||
if (!path.isWithin(root, destination)) {
|
||||
throw FormatException('Invalid download directory: $destination');
|
||||
}
|
||||
var current = root;
|
||||
for (final name in path.split(path.relative(destination, from: root))) {
|
||||
current = path.join(current, name);
|
||||
if (await FileSystemEntity.type(current, followLinks: false) ==
|
||||
FileSystemEntityType.link) {
|
||||
throw FormatException('Download directory contains a link: $current');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool validName(String name, {required bool windows}) {
|
||||
if (name.isEmpty || name == '.' || name == '..' || name.contains('\x00')) {
|
||||
return false;
|
||||
}
|
||||
if (name.contains('/')) return false;
|
||||
return !windows ||
|
||||
(!name.contains(RegExp(r'[<>:"\\|?*]')) &&
|
||||
!name.endsWith('.') &&
|
||||
!name.endsWith(' '));
|
||||
}
|
||||
|
||||
static String mapDirectory(
|
||||
String remoteRoot, String remotePath, String localRoot,
|
||||
{required bool remoteWindows, required bool localWindows}) {
|
||||
final remote = path.Context(
|
||||
style: remoteWindows ? path.Style.windows : path.Style.posix);
|
||||
final local = path.Context(
|
||||
style: localWindows ? path.Style.windows : path.Style.posix);
|
||||
if (remotePath.contains('\x00') ||
|
||||
remote.split(remotePath).contains('..') ||
|
||||
(!remote.equals(remoteRoot, remotePath) &&
|
||||
!remote.isWithin(remoteRoot, remotePath))) {
|
||||
throw FormatException('Invalid download directory: $remotePath');
|
||||
}
|
||||
final relative = remote.relative(remotePath, from: remoteRoot);
|
||||
if (relative == '.') return localRoot;
|
||||
final names = remote.split(relative);
|
||||
if (names.any((name) => !validName(name, windows: localWindows))) {
|
||||
throw FormatException('Invalid download directory: $remotePath');
|
||||
}
|
||||
return local.joinAll([localRoot, ...names]);
|
||||
}
|
||||
}
|
||||
@@ -1928,11 +1928,6 @@ class RustdeskImpl {
|
||||
}
|
||||
|
||||
String mainGetCommonSync({required String key, dynamic hint}) {
|
||||
const prefix = 'resolve-api-server:';
|
||||
if (key.startsWith(prefix)) {
|
||||
return js.context
|
||||
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
|
||||
}
|
||||
throw UnimplementedError("mainGetCommonSync");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
|
||||
void main() {
|
||||
test('warns only for remote HTTP endpoints', () {
|
||||
final cases = <String?, bool>{
|
||||
null: false,
|
||||
'': false,
|
||||
'https://api.example.com': false,
|
||||
'http://api.example.com': true,
|
||||
'http://192.168.1.13:13000': true,
|
||||
'http://localhost:21114': false,
|
||||
'http://127.0.0.1:21114': false,
|
||||
'http://[::1]:21114': false,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('warning follows API and ID changes using the resolved endpoint',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController(text: 'id.example.com');
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
api.isNotEmpty ? api : 'http://$custom',
|
||||
),
|
||||
));
|
||||
expect(find.text('Default HTTP warning'), findsOneWidget);
|
||||
|
||||
id.text = 'localhost';
|
||||
await tester.pump();
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
|
||||
api.text = 'http://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsOneWidget);
|
||||
|
||||
api.text = 'https://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('resolver failures are reported without breaking the server form',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController();
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Column(children: [
|
||||
TextField(controller: api),
|
||||
Expanded(
|
||||
child: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
throw const FormatException('API preview failed'),
|
||||
)),
|
||||
]),
|
||||
),
|
||||
));
|
||||
expect(tester.takeException(), isA<FormatException>());
|
||||
expect(find.byType(ErrorWidget), findsNothing);
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
expect(find.byType(TextField), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_hbb/generated_bridge.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
final _sessionId = UuidValue('00000000-0000-4000-8000-000000000001');
|
||||
|
||||
class _Binding extends Fake implements RustdeskImpl {
|
||||
final sent = <String>[];
|
||||
final created = <String>[];
|
||||
int nextId = 0;
|
||||
|
||||
@override
|
||||
String mainGetCommonSync({required String key, dynamic hint}) =>
|
||||
'${++nextId}';
|
||||
|
||||
@override
|
||||
int versionToNumber({required String v, dynamic hint}) =>
|
||||
v == '1.3.3' ? 1 : 2;
|
||||
|
||||
@override
|
||||
Future<void> sessionSendFiles({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
required String path,
|
||||
required String to,
|
||||
required int fileNum,
|
||||
required bool includeHidden,
|
||||
required bool isRemote,
|
||||
required bool isDir,
|
||||
dynamic hint,
|
||||
}) async {
|
||||
expect(isRemote, isTrue);
|
||||
sent.add(to);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sessionCreateDir({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
required String path,
|
||||
required bool isRemote,
|
||||
dynamic hint,
|
||||
}) async {
|
||||
expect(isRemote, isFalse);
|
||||
created.add(path);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sessionCancelJob({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
dynamic hint,
|
||||
}) async {}
|
||||
}
|
||||
|
||||
class _Session extends Fake implements FFI {
|
||||
@override
|
||||
final String id = 'download-test';
|
||||
@override
|
||||
UuidValue get sessionId => _sessionId;
|
||||
@override
|
||||
late final ffiModel = FfiModel(WeakReference(this));
|
||||
}
|
||||
|
||||
class _Fetcher extends FileFetcher {
|
||||
_Fetcher() : super(() => _sessionId);
|
||||
List<String> emptyDirectories = [];
|
||||
|
||||
@override
|
||||
Future<List<FileDirectory>> readEmptyDirs(
|
||||
String path, bool isLocal, bool showHidden) async =>
|
||||
emptyDirectories.map((path) => FileDirectory()..path = path).toList();
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late _Binding binding;
|
||||
late _Session session;
|
||||
late _Fetcher fetcher;
|
||||
late FileController controller;
|
||||
late DirectoryData destination;
|
||||
|
||||
setUp(() {
|
||||
binding = _Binding();
|
||||
platformFFI.setBindingForTesting(binding);
|
||||
session = _Session();
|
||||
session.ffiModel.pi.version = '1.5.1';
|
||||
fetcher = _Fetcher();
|
||||
destination =
|
||||
DirectoryData(FileDirectory()..path = '/downloads', DirectoryOptions());
|
||||
controller = FileController(
|
||||
isLocal: false,
|
||||
getSessionID: () => _sessionId,
|
||||
rootState: WeakReference(session),
|
||||
jobController: JobController(() => _sessionId, () => null),
|
||||
fileFetcher: fetcher,
|
||||
getOtherSideDirectoryData: () => destination,
|
||||
);
|
||||
controller.directory.value.path = '/remote';
|
||||
});
|
||||
|
||||
tearDown(() => session.ffiModel.dispose());
|
||||
|
||||
Future<void> download(String name, {bool directory = false}) async {
|
||||
final entry = Entry()
|
||||
..name = name
|
||||
..path = '/remote/$name'
|
||||
..entryType = directory ? 0 : 4;
|
||||
final items = SelectedItems(isLocal: false)..add(entry);
|
||||
await controller.sendFiles(items, destination);
|
||||
}
|
||||
|
||||
test('downloads refuse peer listing names that escape the local folder',
|
||||
() async {
|
||||
await download('report.txt');
|
||||
expect(binding.sent, ['/downloads/report.txt']);
|
||||
binding.sent.clear();
|
||||
for (final windows in [false, true]) {
|
||||
destination.options.isWindows = windows;
|
||||
destination.directory.path = windows ? r'C:\downloads' : '/downloads';
|
||||
for (final name in [
|
||||
'../outside.txt',
|
||||
'/outside.txt',
|
||||
'.',
|
||||
'..',
|
||||
'',
|
||||
'bad\x00name',
|
||||
if (windows) ...[r'..\outside.txt', r'C:\outside.txt', r'\\host\share'],
|
||||
]) {
|
||||
await download(name);
|
||||
expect(binding.sent, isEmpty, reason: name);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
}
|
||||
}
|
||||
await controller.jobController.jobDone({
|
||||
'id': '${controller.jobController.jobTable.last.id}',
|
||||
'file_num': '0',
|
||||
});
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
});
|
||||
|
||||
test('empty-directory downloads reject paths outside the selected folder',
|
||||
() async {
|
||||
for (final path in ['/remote/other/empty', '/remote/docs/../out']) {
|
||||
fetcher.emptyDirectories = ['/remote/docs/ok', path];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, isEmpty, reason: path);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
}
|
||||
fetcher.emptyDirectories = ['/remote/docs', '/remote/docs/sub/empty'];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, ['/downloads/docs', '/downloads/docs/sub/empty']);
|
||||
});
|
||||
|
||||
test('empty-directory downloads refuse existing local links', () async {
|
||||
final temporary =
|
||||
await Directory.systemTemp.createTemp('rustdesk_download_');
|
||||
addTearDown(() => temporary.delete(recursive: true));
|
||||
final outside = await Directory('${temporary.path}/outside').create();
|
||||
final downloads = await Directory('${temporary.path}/downloads').create();
|
||||
await Link('${downloads.path}/docs').create(outside.path);
|
||||
destination.directory.path = downloads.path;
|
||||
destination.options.isWindows = Platform.isWindows;
|
||||
fetcher.emptyDirectories = ['/remote/docs/empty'];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, isEmpty);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
});
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/file_manager_page.dart';
|
||||
import 'package:flutter_hbb/desktop/widgets/list_search_action_listener.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
List<Entry> _entries(int count) => [
|
||||
for (var i = 0; i < count; i++)
|
||||
Entry()
|
||||
..name = 'f$i'
|
||||
..path = '/f$i'
|
||||
];
|
||||
|
||||
List<String> _names(List<Entry> entries) =>
|
||||
entries.map((e) => e.name).toList()..sort();
|
||||
|
||||
void main() {
|
||||
test('navigation keys move the selection and stop at the ends', () {
|
||||
final entries = _entries(5);
|
||||
expect(_names(navigateSelection(entries, [], 1, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, [], -1, false)), ['f4']);
|
||||
var selected = navigateSelection(entries, [entries[1]], 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
selected = navigateSelection(entries, selected, -1, false);
|
||||
expect(_names(selected), ['f1']);
|
||||
expect(_names(navigateSelection(entries, selected, -3, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, selected, 5, false)), ['f4']);
|
||||
});
|
||||
|
||||
test('shift extends and shrinks the range from the anchor', () {
|
||||
final entries = _entries(5);
|
||||
var selected = [entries[2]];
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
expect(_names(selected), ['f2', 'f3', 'f4']);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
expect(_names(selected), ['f1', 'f2']);
|
||||
selected = navigateSelection(entries, selected, 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
});
|
||||
|
||||
test('page keys go to the visible edge before paging', () {
|
||||
// Rows 10..19 are fully visible.
|
||||
expect(pageDelta(12, 10, 19, true), 7);
|
||||
expect(pageDelta(19, 10, 19, true), 9);
|
||||
expect(pageDelta(12, 10, 19, false), -2);
|
||||
expect(pageDelta(10, 10, 19, false), -9);
|
||||
});
|
||||
|
||||
testWidgets('Enter does not reach type-to-search', (tester) async {
|
||||
final node = FocusNode();
|
||||
addTearDown(node.dispose);
|
||||
final searched = <String>[];
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ListSearchActionListener(
|
||||
node: node,
|
||||
buffer: TimeoutStringBuffer(),
|
||||
onNext: searched.add,
|
||||
onSearch: searched.add,
|
||||
child: const SizedBox(),
|
||||
),
|
||||
));
|
||||
node.requestFocus();
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter, character: '\r');
|
||||
expect(searched, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
#include "win32_desktop.h"
|
||||
#include "flutter_window.h"
|
||||
#include "utils.h"
|
||||
#include "service_control.h"
|
||||
|
||||
typedef char** (*FUNC_RUSTDESK_CORE_MAIN)(int*);
|
||||
typedef void (*FUNC_RUSTDESK_FREE_ARGS)( char**, int);
|
||||
@@ -24,9 +23,6 @@ const wchar_t* getWindowClassName();
|
||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||
_In_ wchar_t *command_line, _In_ int show_command)
|
||||
{
|
||||
if (auto result = service_control::HandleCommand(command_line)) {
|
||||
return static_cast<int>(*result);
|
||||
}
|
||||
HINSTANCE hInstance = LoadLibraryA("librustdesk.dll");
|
||||
if (!hInstance)
|
||||
{
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
#ifndef RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
#define RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
|
||||
#include <windows.h>
|
||||
#include <shellapi.h>
|
||||
#include <winsvc.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cwchar>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace service_control {
|
||||
|
||||
using ServiceHandle = std::unique_ptr<std::remove_pointer_t<SC_HANDLE>,
|
||||
decltype(&CloseServiceHandle)>;
|
||||
constexpr DWORD kStopTimeoutMilliseconds = 30000;
|
||||
constexpr DWORD kPollIntervalMilliseconds = 100;
|
||||
|
||||
inline DWORD StopService(SC_HANDLE service) {
|
||||
SERVICE_STATUS_PROCESS status{};
|
||||
DWORD bytes_needed = 0;
|
||||
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
|
||||
reinterpret_cast<BYTE*>(&status), sizeof(status),
|
||||
&bytes_needed)) {
|
||||
return GetLastError();
|
||||
}
|
||||
if (status.dwCurrentState == SERVICE_STOPPED) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
if (status.dwCurrentState != SERVICE_STOP_PENDING) {
|
||||
SERVICE_STATUS stopped{};
|
||||
if (!ControlService(service, SERVICE_CONTROL_STOP, &stopped)) {
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_NOT_ACTIVE ? ERROR_SUCCESS : error;
|
||||
}
|
||||
}
|
||||
// The installer may remove files next; accepting STOP alone does not mean
|
||||
// the service has reached SERVICE_STOPPED.
|
||||
const ULONGLONG started = GetTickCount64();
|
||||
while (status.dwCurrentState != SERVICE_STOPPED) {
|
||||
if (GetTickCount64() - started >= kStopTimeoutMilliseconds) {
|
||||
return ERROR_TIMEOUT;
|
||||
}
|
||||
Sleep(kPollIntervalMilliseconds);
|
||||
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
|
||||
reinterpret_cast<BYTE*>(&status), sizeof(status),
|
||||
&bytes_needed)) {
|
||||
return GetLastError();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
inline DWORD RemoveService(const wchar_t* name) {
|
||||
ServiceHandle manager(OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT),
|
||||
CloseServiceHandle);
|
||||
if (!manager) {
|
||||
return GetLastError();
|
||||
}
|
||||
ServiceHandle service(
|
||||
OpenServiceW(manager.get(), name,
|
||||
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE),
|
||||
CloseServiceHandle);
|
||||
if (!service) {
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_DOES_NOT_EXIST ? ERROR_SUCCESS : error;
|
||||
}
|
||||
const DWORD stopped = StopService(service.get());
|
||||
if (stopped != ERROR_SUCCESS) {
|
||||
// The uninstall script must still reach its taskkill cleanup.
|
||||
std::fwprintf(stderr,
|
||||
L"Service did not stop cleanly: Windows error %lu\n", stopped);
|
||||
}
|
||||
if (DeleteService(service.get())) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_MARKED_FOR_DELETE ? ERROR_SUCCESS : error;
|
||||
}
|
||||
|
||||
inline DWORD InstallService(const wchar_t* name, const wchar_t* executable,
|
||||
bool rollback_on_failure) {
|
||||
if (!*executable || wcschr(executable, L'"')) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
const std::wstring binary_path =
|
||||
L"\"" + std::wstring(executable) + L"\" --service";
|
||||
const std::wstring display_name = std::wstring(name) + L" Service";
|
||||
ServiceHandle manager(
|
||||
OpenSCManagerW(nullptr, nullptr,
|
||||
SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE),
|
||||
CloseServiceHandle);
|
||||
if (!manager) {
|
||||
return GetLastError();
|
||||
}
|
||||
ServiceHandle service(
|
||||
CreateServiceW(manager.get(), name, display_name.c_str(),
|
||||
SERVICE_START | DELETE, SERVICE_WIN32_OWN_PROCESS,
|
||||
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
|
||||
binary_path.c_str(), nullptr,
|
||||
nullptr, nullptr, nullptr, nullptr),
|
||||
CloseServiceHandle);
|
||||
const bool created = service != nullptr;
|
||||
// --after-install can reuse a registration. Preserve its executable and
|
||||
// account, as the previous create-then-start script did.
|
||||
if (!service && GetLastError() == ERROR_SERVICE_EXISTS) {
|
||||
service.reset(OpenServiceW(manager.get(), name, SERVICE_START));
|
||||
}
|
||||
if (!service) {
|
||||
return GetLastError();
|
||||
}
|
||||
if (StartServiceW(service.get(), 0, nullptr)) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
const DWORD error = GetLastError();
|
||||
// Only manual Start Service restores stop-service=Y on failure. Other
|
||||
// installation paths retain the registration for a later startup attempt.
|
||||
if (rollback_on_failure && created && error != ERROR_SERVICE_ALREADY_RUNNING &&
|
||||
!DeleteService(service.get())) {
|
||||
const DWORD rollback_error = GetLastError();
|
||||
std::fwprintf(stderr,
|
||||
L"Failed to roll back newly created service: Windows error %lu\n",
|
||||
rollback_error);
|
||||
}
|
||||
return error == ERROR_SERVICE_ALREADY_RUNNING ? ERROR_SUCCESS : error;
|
||||
}
|
||||
|
||||
inline DWORD RunCommand(int count, wchar_t** args) {
|
||||
constexpr int kRemoveArgumentCount = 4;
|
||||
constexpr int kInstallArgumentCount = 5;
|
||||
if (count < kRemoveArgumentCount) {
|
||||
return ERROR_BAD_ARGUMENTS;
|
||||
}
|
||||
if (!*args[3]) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
const std::wstring_view operation(args[2]);
|
||||
const bool rollback_on_failure = operation == L"create-service-with-rollback";
|
||||
if ((operation == L"create-service" || rollback_on_failure) &&
|
||||
count == kInstallArgumentCount) {
|
||||
return InstallService(args[3], args[4], rollback_on_failure);
|
||||
}
|
||||
if (operation == L"remove" && count == kRemoveArgumentCount) {
|
||||
return RemoveService(args[3]);
|
||||
}
|
||||
return ERROR_BAD_ARGUMENTS;
|
||||
}
|
||||
|
||||
// Keep these commands in the existing runner so installation/removal can control
|
||||
// services before loading librustdesk.dll or initializing the UI. A Rust-side
|
||||
// handler would first require that DLL to load. The header-only implementation
|
||||
// keeps main.cpp as a dispatch hook without adding a CMake source entry; it is
|
||||
// compiled into the existing EXE, not a separately packaged helper.
|
||||
inline std::optional<DWORD> HandleCommand(const wchar_t* command_line) {
|
||||
constexpr std::wstring_view option = L"--service-control";
|
||||
const std::wstring_view arguments(command_line);
|
||||
if (arguments.compare(0, option.size(), option) != 0 ||
|
||||
(arguments.size() > option.size() && arguments[option.size()] != L' ' &&
|
||||
arguments[option.size()] != L'\t')) {
|
||||
return std::nullopt;
|
||||
}
|
||||
int count = 0;
|
||||
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
|
||||
if (!args) {
|
||||
return GetLastError();
|
||||
}
|
||||
const DWORD result = RunCommand(count, args);
|
||||
LocalFree(args);
|
||||
if (result != ERROR_SUCCESS) {
|
||||
std::fwprintf(stderr,
|
||||
L"RustDesk service control failed with Windows error %lu\n",
|
||||
result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace service_control
|
||||
|
||||
#endif // RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
@@ -311,7 +311,6 @@ pub const KEYS_SETTINGS: &[&str] = &[
|
||||
OPTION_API_SERVER,
|
||||
OPTION_KEY,
|
||||
OPTION_ALLOW_WEBSOCKET,
|
||||
OPTION_WEBSOCKET_PORT,
|
||||
OPTION_PRESET_ADDRESS_BOOK_NAME,
|
||||
OPTION_PRESET_ADDRESS_BOOK_TAG,
|
||||
OPTION_PRESET_ADDRESS_BOOK_ALIAS,
|
||||
|
||||
+1
-37
@@ -27,12 +27,6 @@ use hbb_common::{
|
||||
|
||||
static NEXT_JOB_ID: AtomicI32 = AtomicI32::new(1);
|
||||
|
||||
pub mod download;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fs/download_tests.rs"]
|
||||
mod download_tests;
|
||||
|
||||
pub fn get_next_job_id() -> i32 {
|
||||
NEXT_JOB_ID.fetch_add(1, Ordering::SeqCst)
|
||||
}
|
||||
@@ -423,8 +417,6 @@ pub struct TransferJob {
|
||||
default_overwrite_strategy: Option<bool>,
|
||||
#[serde(skip_serializing)]
|
||||
digest: FileDigest,
|
||||
#[serde(skip)]
|
||||
download: Option<download::DownloadState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
@@ -595,7 +587,6 @@ impl TransferJob {
|
||||
files: Vec::new(),
|
||||
total_size: 0,
|
||||
enable_overwrite_detection,
|
||||
download: (is_remote && r#type == JobType::Generic).then(Default::default),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -657,9 +648,6 @@ impl TransferJob {
|
||||
|
||||
#[inline]
|
||||
pub fn set_files(&mut self, files: Vec<FileEntry>) -> ResultType<()> {
|
||||
if self.is_download() && !self.files.is_empty() {
|
||||
bail!("cannot replace an accepted download file list");
|
||||
}
|
||||
validate_transfer_file_names(&files)?;
|
||||
if let DataSource::FilePath(base) = &self.data_source {
|
||||
for file in &files {
|
||||
@@ -704,12 +692,7 @@ impl TransferJob {
|
||||
|
||||
fn resolve_entry_path(&self, base: &PathBuf, name: &str) -> Option<PathBuf> {
|
||||
if self.r#type == JobType::Generic {
|
||||
let result = if self.is_download() {
|
||||
download::validated_target(base, name)
|
||||
} else {
|
||||
join_validated_path(base, name)
|
||||
};
|
||||
match result {
|
||||
match join_validated_path(base, name) {
|
||||
Ok(path) => Some(path),
|
||||
Err(err) => {
|
||||
log::error!("Invalid file name in transfer job {}: {}", self.id, err);
|
||||
@@ -722,12 +705,6 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub fn modify_time(&self) {
|
||||
if self.is_download() {
|
||||
if let Err(err) = self.finish_download() {
|
||||
log::error!("Failed to finish download {}: {}", self.id, err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.r#type == JobType::Printer {
|
||||
return;
|
||||
}
|
||||
@@ -752,9 +729,6 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub fn remove_download_file(&self) {
|
||||
if self.is_download() && self.data_stream.is_none() {
|
||||
return;
|
||||
}
|
||||
if self.r#type == JobType::Printer {
|
||||
return;
|
||||
}
|
||||
@@ -787,9 +761,6 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub async fn write(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if self.is_download() {
|
||||
return self.write_download(block).await;
|
||||
}
|
||||
if block.id != self.id {
|
||||
bail!("Wrong id");
|
||||
}
|
||||
@@ -1189,13 +1160,6 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub async fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
|
||||
if self.is_download() {
|
||||
self.confirm_download(r);
|
||||
// Open receiver resume streams in write() so validation errors reach the caller.
|
||||
if matches!(r.union, Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) if offset > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if self.file_num() != r.file_num {
|
||||
// This branch will always be hit if:
|
||||
// 1. `confirm()` is called in `ui_cm_interface.rs`
|
||||
|
||||
@@ -1,331 +0,0 @@
|
||||
use super::{
|
||||
get_string, is_write_need_confirmation, join_validated_path, validate_file_name_no_traversal,
|
||||
validate_no_symlink_components, DataSource, DataStream, DigestCheckResult, TransferJob,
|
||||
};
|
||||
use crate::message_proto::{
|
||||
file_transfer_send_confirm_request, FileEntry, FileTransferBlock, FileTransferDigest,
|
||||
FileTransferSendConfirmRequest, FileType,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
io::ErrorKind,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tokio::{
|
||||
fs::{self, OpenOptions},
|
||||
io::{AsyncSeekExt, AsyncWriteExt},
|
||||
};
|
||||
|
||||
const SINGLE_LINK_COUNT: u64 = 1;
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct DownloadState {
|
||||
pub(super) confirmation: Option<(i32, u32)>,
|
||||
}
|
||||
|
||||
pub fn validate_listing(entries: &[FileEntry], peer_windows: bool) -> ResultType<()> {
|
||||
for entry in entries {
|
||||
let name = &entry.name;
|
||||
if entry.entry_type.enum_value() == Ok(FileType::DirDrive)
|
||||
&& matches!(name.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if name.is_empty()
|
||||
|| name == "."
|
||||
|| name == ".."
|
||||
|| name.contains('\0')
|
||||
|| name.contains('/')
|
||||
|| (peer_windows
|
||||
&& (name.contains('\\')
|
||||
|| matches!(name.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())))
|
||||
{
|
||||
bail!("invalid file name in remote directory listing: {name}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_download_name(path: &str, peer_windows: bool) -> ResultType<()> {
|
||||
let separator = |c| c == '/' || (peer_windows && c == '\\');
|
||||
let path = path.trim_end_matches(separator);
|
||||
validate_component(path.rsplit(separator).next().unwrap_or(""))
|
||||
}
|
||||
|
||||
fn validate_component(name: &str) -> ResultType<()> {
|
||||
validate_file_name_no_traversal(name)?;
|
||||
if name.is_empty() || name == "." || name.contains('/') {
|
||||
bail!("invalid download file name: {name}");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if name.contains(['\\', ':', '<', '>', '"', '|', '?', '*'])
|
||||
|| name.ends_with('.')
|
||||
|| name.ends_with(' ')
|
||||
{
|
||||
bail!("invalid Windows download file name: {name}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validated_target(base: &PathBuf, name: &str) -> ResultType<PathBuf> {
|
||||
let parent = base
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("download destination has no parent"))?;
|
||||
let leaf = base
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| anyhow!("invalid download destination"))?;
|
||||
validate_component(leaf)?;
|
||||
#[cfg(windows)]
|
||||
for component in name.split(['/', '\\']).filter(|part| !part.is_empty()) {
|
||||
validate_component(component)?;
|
||||
}
|
||||
validate_no_symlink_components(&parent.to_path_buf(), leaf)?;
|
||||
let target = join_validated_path(base, name)?;
|
||||
let parent = target
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("download file has no parent"))?;
|
||||
let leaf = target
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| anyhow!("invalid download file name"))?;
|
||||
for suffix in ["download", "digest"] {
|
||||
validate_no_symlink_components(&parent.to_path_buf(), &format!("{leaf}.{suffix}"))?;
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
fn remove_if_exists(path: &Path) -> ResultType<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_if_exists_async(path: &Path) -> ResultType<()> {
|
||||
match fs::remove_file(path).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_resume_file(file: &tokio::fs::File) -> ResultType<()> {
|
||||
let metadata = file.metadata().await?;
|
||||
if !metadata.is_file() {
|
||||
bail!("download resume staging path is not a regular file");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let links = std::os::unix::fs::MetadataExt::nlink(&metadata);
|
||||
#[cfg(windows)]
|
||||
let links = {
|
||||
use std::{mem::MaybeUninit, os::windows::io::AsRawHandle};
|
||||
use winapi::{
|
||||
shared::minwindef::FALSE,
|
||||
um::fileapi::{GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION},
|
||||
};
|
||||
let file = file.try_clone().await?;
|
||||
tokio::task::spawn_blocking(move || -> ResultType<u64> {
|
||||
let mut information = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
|
||||
if unsafe {
|
||||
GetFileInformationByHandle(file.as_raw_handle() as _, information.as_mut_ptr())
|
||||
} == FALSE
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(u64::from(
|
||||
unsafe { information.assume_init() }.nNumberOfLinks,
|
||||
))
|
||||
})
|
||||
.await??
|
||||
};
|
||||
if links != SINGLE_LINK_COUNT {
|
||||
bail!("hard-linked download resume staging file is not allowed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl TransferJob {
|
||||
pub(super) fn is_download(&self) -> bool {
|
||||
self.download.is_some()
|
||||
}
|
||||
|
||||
pub fn download_target(&self, file_num: i32) -> ResultType<PathBuf> {
|
||||
let entry = self
|
||||
.files
|
||||
.get(file_num as usize)
|
||||
.ok_or_else(|| anyhow!("Wrong file number"))?;
|
||||
let DataSource::FilePath(base) = &self.data_source else {
|
||||
bail!("download destination is not a file path");
|
||||
};
|
||||
validated_target(base, &entry.name)
|
||||
}
|
||||
|
||||
pub fn download_digest(
|
||||
&mut self,
|
||||
can_resume: bool,
|
||||
digest: &FileTransferDigest,
|
||||
) -> ResultType<DigestCheckResult> {
|
||||
if self.file_num != digest.file_num && self.data_stream.is_some() {
|
||||
let result = self.finish_download();
|
||||
self.data_stream.take();
|
||||
result?;
|
||||
}
|
||||
let target = self.download_target(digest.file_num)?;
|
||||
let resume = can_resume && self.is_resume && !target.try_exists()?;
|
||||
let result = is_write_need_confirmation(resume, &get_string(&target), digest)?;
|
||||
if matches!(result, DigestCheckResult::NoSuchFile)
|
||||
&& (Path::new(&format!("{}.download", target.display())).try_exists()?
|
||||
|| Path::new(&format!("{}.digest", target.display())).try_exists()?)
|
||||
{
|
||||
return Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
|
||||
id: digest.id,
|
||||
file_num: digest.file_num,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn confirm_download(&mut self, request: &FileTransferSendConfirmRequest) {
|
||||
if request.id != self.id {
|
||||
return;
|
||||
}
|
||||
let Some(download) = self.download.as_mut() else {
|
||||
return;
|
||||
};
|
||||
download.confirmation = self.files.get(request.file_num as usize).and_then(|_| {
|
||||
let offset = match request.union {
|
||||
Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) => offset,
|
||||
Some(file_transfer_send_confirm_request::Union::Skip(false)) => 0,
|
||||
_ => return None,
|
||||
};
|
||||
Some((request.file_num, offset))
|
||||
});
|
||||
}
|
||||
|
||||
fn download_confirmation_offset(&self, file_num: i32) -> Option<u32> {
|
||||
let (confirmed, offset) = self.download.as_ref()?.confirmation.as_ref()?;
|
||||
(*confirmed == file_num).then_some(*offset)
|
||||
}
|
||||
|
||||
async fn start_download_file(&mut self, file_num: i32) -> ResultType<()> {
|
||||
let result = self.finish_download();
|
||||
self.data_stream.take();
|
||||
result?;
|
||||
let target = self.download_target(file_num)?;
|
||||
let staging = PathBuf::from(format!("{}.download", target.display()));
|
||||
let digest = PathBuf::from(format!("{}.digest", target.display()));
|
||||
let confirmation = self.download_confirmation_offset(file_num);
|
||||
if (fs::try_exists(&target).await?
|
||||
|| fs::try_exists(&staging).await?
|
||||
|| fs::try_exists(&digest).await?)
|
||||
&& confirmation.is_none()
|
||||
{
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
if let Some(offset) = confirmation.filter(|offset| *offset > 0) {
|
||||
return self.resume_download(file_num, offset).await;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent).await?;
|
||||
}
|
||||
remove_if_exists_async(&staging).await?;
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&staging)
|
||||
.await?;
|
||||
self.file_num = file_num;
|
||||
self.data_stream = Some(DataStream::FileStream(file));
|
||||
remove_if_exists_async(&digest).await?;
|
||||
let mut metadata = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&digest)
|
||||
.await?;
|
||||
metadata
|
||||
.write_all(serde_json::to_string(&self.digest)?.as_bytes())
|
||||
.await?;
|
||||
metadata.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn resume_download(&mut self, file_num: i32, offset: u32) -> ResultType<()> {
|
||||
let target = self.download_target(file_num)?;
|
||||
if fs::try_exists(&target).await? {
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
let digest = fs::metadata(format!("{}.digest", target.display())).await?;
|
||||
if !digest.is_file() {
|
||||
bail!("download resume metadata is not a regular file");
|
||||
}
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(format!("{}.download", target.display()))
|
||||
.await?;
|
||||
validate_resume_file(&file).await?;
|
||||
if file.metadata().await?.len() != u64::from(offset) {
|
||||
bail!("download resume offset does not match staging file size");
|
||||
}
|
||||
file.seek(std::io::SeekFrom::Start(u64::from(offset)))
|
||||
.await?;
|
||||
self.file_num = file_num;
|
||||
self.data_stream = Some(DataStream::FileStream(file));
|
||||
self.transferred += u64::from(offset);
|
||||
self.finished_size += u64::from(offset);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn write_download(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if block.id != self.id {
|
||||
bail!("Wrong id");
|
||||
}
|
||||
if block.file_num as usize >= self.files.len() {
|
||||
bail!("Wrong file number");
|
||||
}
|
||||
if block.file_num != self.file_num || self.data_stream.is_none() {
|
||||
self.start_download_file(block.file_num).await?;
|
||||
}
|
||||
let data = if block.compressed {
|
||||
Cow::Owned(decompress(&block.data))
|
||||
} else {
|
||||
Cow::Borrowed(block.data.as_ref())
|
||||
};
|
||||
let Some(DataStream::FileStream(stream)) = self.data_stream.as_mut() else {
|
||||
bail!("download file stream is missing");
|
||||
};
|
||||
stream.write_all(&data).await?;
|
||||
stream.flush().await?;
|
||||
self.finished_size += data.len() as u64;
|
||||
self.transferred += block.data.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn finish_download(&self) -> ResultType<()> {
|
||||
if !self.is_download() {
|
||||
self.modify_time();
|
||||
return Ok(());
|
||||
}
|
||||
if self.data_stream.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let target = self.download_target(self.file_num)?;
|
||||
if target.try_exists()? && self.download_confirmation_offset(self.file_num) != Some(0) {
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
std::fs::rename(format!("{}.download", target.display()), &target)?;
|
||||
remove_if_exists(&PathBuf::from(format!("{}.digest", target.display())))?;
|
||||
let entry = self
|
||||
.files
|
||||
.get(self.file_num as usize)
|
||||
.ok_or_else(|| anyhow!("Wrong file number"))?;
|
||||
filetime::set_file_mtime(
|
||||
&target,
|
||||
filetime::FileTime::from_unix_time(entry.modified_time as _, 0),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
struct DownloadDir(PathBuf);
|
||||
|
||||
impl DownloadDir {
|
||||
fn new() -> Self {
|
||||
static NEXT_DIRECTORY: AtomicI32 = AtomicI32::new(1);
|
||||
let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rustdesk_download_{}_{nonce}_{sequence}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn job(&self) -> TransferJob {
|
||||
self.job_with_files(vec![FileEntry::default()])
|
||||
}
|
||||
|
||||
fn job_with_files(&self, files: Vec<FileEntry>) -> TransferJob {
|
||||
TransferJob::new_write(
|
||||
1,
|
||||
JobType::Generic,
|
||||
"/remote/file.txt".into(),
|
||||
DataSource::FilePath(self.0.join("file.txt")),
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
)
|
||||
.with_files(files)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DownloadDir {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn block() -> FileTransferBlock {
|
||||
FileTransferBlock {
|
||||
id: 1,
|
||||
file_num: 0,
|
||||
data: b"received".to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn approval(file_num: i32, offset: u32) -> FileTransferSendConfirmRequest {
|
||||
FileTransferSendConfirmRequest {
|
||||
id: 1,
|
||||
file_num,
|
||||
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_listing_rejects_unsafe_names_and_keeps_drive_rows() {
|
||||
for name in ["../outside", "/outside", ".", "..", "", "dir/file"] {
|
||||
let entry = FileEntry {
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
download::validate_listing(&[entry], false).is_err(),
|
||||
"{}",
|
||||
name
|
||||
);
|
||||
}
|
||||
let entries = [
|
||||
FileEntry {
|
||||
name: "report.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "report:notes".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "C:".into(),
|
||||
entry_type: FileType::DirDrive.into(),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
download::validate_listing(&entries, true).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_requires_confirmation_to_overwrite() {
|
||||
let dir = DownloadDir::new();
|
||||
let target = dir.0.join("file.txt");
|
||||
std::fs::write(&target, b"original").unwrap();
|
||||
let mut job = dir.job();
|
||||
assert!(job.write(block()).await.is_err());
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"original");
|
||||
assert!(!dir.0.join("file.txt.download").exists());
|
||||
|
||||
job.confirm(&approval(0, 0)).await;
|
||||
job.write(block()).await.unwrap();
|
||||
assert!(job.set_files(vec![FileEntry::default()]).is_err());
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"received");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_requires_separate_confirmation_for_each_existing_file() {
|
||||
let dir = DownloadDir::new();
|
||||
let mut job = dir.job_with_files(vec![
|
||||
FileEntry {
|
||||
name: "first.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "second.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
]);
|
||||
job.write(block()).await.unwrap();
|
||||
let second = dir.0.join("file.txt/second.txt");
|
||||
std::fs::write(&second, b"original").unwrap();
|
||||
assert!(job
|
||||
.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.is_err());
|
||||
assert_eq!(std::fs::read(&second).unwrap(), b"original");
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt/first.txt")).unwrap(),
|
||||
b"received"
|
||||
);
|
||||
job.confirm(&approval(1, 0)).await;
|
||||
job.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(&second).unwrap(), b"received");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_preserves_received_files_when_publication_fails() {
|
||||
for next_is_digest in [false, true] {
|
||||
let dir = DownloadDir::new();
|
||||
let files = ["first.txt", "second.txt"]
|
||||
.iter()
|
||||
.map(|&name| FileEntry {
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let mut job = dir.job_with_files(files);
|
||||
job.write(block()).await.unwrap();
|
||||
let target = dir.0.join("file.txt/first.txt");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
if next_is_digest {
|
||||
assert!(job
|
||||
.download_digest(
|
||||
true,
|
||||
&FileTransferDigest {
|
||||
id: 1,
|
||||
file_num: 1,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.is_err());
|
||||
} else {
|
||||
assert!(job
|
||||
.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.is_err());
|
||||
}
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt/first.txt.download")).unwrap(),
|
||||
b"received"
|
||||
);
|
||||
assert!(dir.0.join("file.txt/first.txt.digest").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_recovers_interrupted_transfer() {
|
||||
for (resuming, changed) in [(false, false), (true, true), (true, false)] {
|
||||
let dir = DownloadDir::new();
|
||||
let mut digest = FileTransferDigest {
|
||||
id: 1,
|
||||
file_size: block().data.len() as _,
|
||||
last_modified: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let mut interrupted = dir.job();
|
||||
interrupted.set_digest(digest.file_size, digest.last_modified);
|
||||
let partial = FileTransferBlock {
|
||||
data: b"rec".to_vec().into(),
|
||||
..block()
|
||||
};
|
||||
interrupted.write(partial).await.unwrap();
|
||||
drop(interrupted);
|
||||
|
||||
let mut job = dir.job();
|
||||
job.is_resume = resuming;
|
||||
digest.last_modified += u64::from(changed);
|
||||
job.set_digest(digest.file_size, digest.last_modified);
|
||||
let confirmation = match job.download_digest(true, &digest).unwrap() {
|
||||
DigestCheckResult::NeedConfirm(confirmation) => confirmation,
|
||||
_ => panic!("interrupted download must require confirmation"),
|
||||
};
|
||||
let offset = if resuming && !changed {
|
||||
b"rec".len()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
assert_eq!(confirmation.is_identical, offset > 0);
|
||||
assert_eq!(confirmation.transferred_size, offset as u64);
|
||||
assert!(job.write(block()).await.is_err());
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt.download")).unwrap(),
|
||||
b"rec"
|
||||
);
|
||||
job.confirm(&approval(0, offset as _)).await;
|
||||
job.write(FileTransferBlock {
|
||||
data: block().data.slice(offset..),
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(dir.0.join("file.txt")).unwrap(), b"received");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_does_not_publish_or_remove_unreceived_staging_files() {
|
||||
let dir = DownloadDir::new();
|
||||
let target = dir.0.join("file.txt");
|
||||
let staging = dir.0.join("file.txt.download");
|
||||
std::fs::write(&target, b"original").unwrap();
|
||||
std::fs::write(&staging, b"another transfer").unwrap();
|
||||
let job = dir.job();
|
||||
job.modify_time();
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(&staging).unwrap(), b"another transfer");
|
||||
|
||||
let metadata_only = DownloadDir::new();
|
||||
let metadata = metadata_only.0.join("file.txt.digest");
|
||||
std::fs::write(&metadata, b"unrelated file").unwrap();
|
||||
assert!(metadata_only.job().write(block()).await.is_err());
|
||||
assert_eq!(std::fs::read(metadata).unwrap(), b"unrelated file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn download_rejects_windows_streams_and_ambiguous_components() {
|
||||
let dir = DownloadDir::new();
|
||||
for name in ["nested/file:stream", "nested/.. /outside", "nested/file."] {
|
||||
assert!(
|
||||
download::validated_target(&dir.0.join("docs"), name).is_err(),
|
||||
"{}",
|
||||
name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg_attr(windows, ignore = "requires symlink privilege")]
|
||||
async fn download_refuses_symlink_destination_directory() {
|
||||
let dir = DownloadDir::new();
|
||||
let outside = dir.0.join("outside");
|
||||
let link = dir.0.join("file.txt");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&outside, &link).unwrap();
|
||||
#[cfg(windows)]
|
||||
std::os::windows::fs::symlink_dir(&outside, &link).unwrap();
|
||||
let mut job = dir.job_with_files(vec![FileEntry {
|
||||
name: "child.txt".into(),
|
||||
..Default::default()
|
||||
}]);
|
||||
assert!(job.write(block()).await.is_err());
|
||||
job.modify_time();
|
||||
assert!(!outside.join("child.txt").exists());
|
||||
assert!(!outside.join("child.txt.download").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg_attr(windows, ignore = "requires symlink privilege")]
|
||||
async fn download_refuses_linked_target_and_staging_files() {
|
||||
for suffix in ["", ".download", ".digest"] {
|
||||
let dir = DownloadDir::new();
|
||||
let outside = dir.0.join("outside.txt");
|
||||
let link = dir.0.join(format!("file.txt{suffix}"));
|
||||
std::fs::write(&outside, b"original").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&outside, &link).unwrap();
|
||||
#[cfg(windows)]
|
||||
std::os::windows::fs::symlink_file(&outside, &link).unwrap();
|
||||
let mut job = dir.job();
|
||||
assert!(job.write(block()).await.is_err());
|
||||
job.modify_time();
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"original");
|
||||
assert!(std::fs::symlink_metadata(link)
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink());
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule libs/hbb_common updated: edefa08b79...5d52530b63
@@ -25,9 +25,6 @@ use hwcodec::{
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(all(test, windows, feature = "vram"))]
|
||||
mod tests;
|
||||
|
||||
const DEFAULT_PIXFMT: AVPixelFormat = AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
pub const DEFAULT_FPS: i32 = 30;
|
||||
const DEFAULT_GOP: i32 = i32::MAX;
|
||||
@@ -239,7 +236,7 @@ impl HwRamEncoder {
|
||||
data.append(v);
|
||||
Ok(data)
|
||||
}
|
||||
Err(code) => Err(anyhow!("RAM encode failed: {}", code)),
|
||||
Err(_) => Ok(Vec::<EncodeFrame>::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
use super::{CodecInfo, HwCodecConfig, CONFIG, CONFIG_SET_BY_IPC};
|
||||
use crate::{
|
||||
codec::enable_vram_option,
|
||||
vram::{VRamDecoder, VRamEncoder},
|
||||
AdapterDevice, CodecFormat,
|
||||
};
|
||||
use base::config::keys::{OPTION_ALLOW_D3D_RENDER, OPTION_ENABLE_HWCODEC};
|
||||
use hbb_common::config::{OVERWRITE_LOCAL_SETTINGS, OVERWRITE_SETTINGS};
|
||||
use hwcodec::{
|
||||
common::{DataFormat, Driver},
|
||||
vram::{DecodeContext, FeatureContext},
|
||||
};
|
||||
use std::{collections::HashMap, mem};
|
||||
|
||||
struct RestoreConfig {
|
||||
config: Option<HwCodecConfig>,
|
||||
set_by_ipc: bool,
|
||||
options: HashMap<String, String>,
|
||||
local_options: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Drop for RestoreConfig {
|
||||
fn drop(&mut self) {
|
||||
*CONFIG.lock().unwrap() = self.config.take();
|
||||
*CONFIG_SET_BY_IPC.lock().unwrap() = self.set_by_ipc;
|
||||
*OVERWRITE_SETTINGS.write().unwrap() = mem::take(&mut self.options);
|
||||
*OVERWRITE_LOCAL_SETTINGS.write().unwrap() = mem::take(&mut self.local_options);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_backend(config: &mut HwCodecConfig, driver: Driver, vendor: Driver, format: DataFormat) {
|
||||
let luid = match vendor {
|
||||
Driver::NV => 1,
|
||||
Driver::MFX => 2,
|
||||
Driver::AMF => 3,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
config.vram_encode.push(FeatureContext {
|
||||
driver: driver.clone(),
|
||||
vendor: vendor.clone(),
|
||||
luid,
|
||||
data_format: format,
|
||||
});
|
||||
config.vram_decode.push(DecodeContext {
|
||||
device: None,
|
||||
driver,
|
||||
vendor,
|
||||
luid,
|
||||
data_format: format,
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_sdk_entries_are_ignored_before_check_completes() {
|
||||
let _restore = RestoreConfig {
|
||||
config: CONFIG.lock().unwrap().take(),
|
||||
set_by_ipc: mem::replace(&mut *CONFIG_SET_BY_IPC.lock().unwrap(), false),
|
||||
options: mem::take(&mut *OVERWRITE_SETTINGS.write().unwrap()),
|
||||
local_options: mem::take(&mut *OVERWRITE_LOCAL_SETTINGS.write().unwrap()),
|
||||
};
|
||||
OVERWRITE_SETTINGS
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(OPTION_ENABLE_HWCODEC.into(), "Y".into());
|
||||
OVERWRITE_LOCAL_SETTINGS
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(OPTION_ALLOW_D3D_RENDER.into(), "Y".into());
|
||||
assert!(enable_vram_option(false));
|
||||
|
||||
let formats = [
|
||||
(CodecFormat::H264, DataFormat::H264),
|
||||
(CodecFormat::H265, DataFormat::H265),
|
||||
];
|
||||
let mut cached = HwCodecConfig::default();
|
||||
for (_, format) in formats {
|
||||
// A RAM fallback keeps this selection test independent of attached displays.
|
||||
cached.ram_encode.push(CodecInfo {
|
||||
format,
|
||||
..Default::default()
|
||||
});
|
||||
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
|
||||
add_backend(&mut cached, vendor.clone(), vendor, format);
|
||||
}
|
||||
}
|
||||
*CONFIG.lock().unwrap() = Some(cached.clone());
|
||||
assert!(!HwCodecConfig::already_set());
|
||||
for (format, _) in formats {
|
||||
assert!(VRamEncoder::available(format).is_empty());
|
||||
for luid in 1..=3 {
|
||||
assert!(VRamDecoder::try_get(format, Some(luid)).is_none());
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
VRamDecoder::possible_available_without_check(),
|
||||
(false, false)
|
||||
);
|
||||
|
||||
for (index, &(format, data_format)) in formats.iter().enumerate() {
|
||||
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
|
||||
add_backend(&mut cached, Driver::FFMPEG, vendor, data_format);
|
||||
}
|
||||
*CONFIG.lock().unwrap() = Some(cached.clone());
|
||||
let encoders = VRamEncoder::available(format);
|
||||
assert_eq!(encoders.len(), 3);
|
||||
for encoder in encoders {
|
||||
assert_eq!(encoder.driver, Driver::FFMPEG);
|
||||
let device = AdapterDevice {
|
||||
luid: encoder.luid,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(VRamEncoder::try_get(&device, format), Some(encoder.clone()));
|
||||
let decoder = VRamDecoder::try_get(format, Some(encoder.luid)).unwrap();
|
||||
assert_eq!(decoder.driver, Driver::FFMPEG);
|
||||
assert_eq!(decoder.vendor, encoder.vendor);
|
||||
assert_eq!(decoder.data_format, data_format);
|
||||
}
|
||||
assert!(VRamDecoder::available(format, Some(99)).is_empty());
|
||||
assert!(VRamDecoder::available(format, None).is_empty());
|
||||
assert_eq!(
|
||||
VRamDecoder::possible_available_without_check(),
|
||||
(true, index == 1)
|
||||
);
|
||||
}
|
||||
assert!(!HwCodecConfig::already_set());
|
||||
assert_eq!(
|
||||
HwCodecConfig::get().vram_encode.len(),
|
||||
cached.vram_encode.len()
|
||||
);
|
||||
}
|
||||
@@ -209,8 +209,6 @@ impl Frame<'_> {
|
||||
pub enum EncodeInput<'a> {
|
||||
YUV(&'a [u8]),
|
||||
Texture((*mut c_void, usize)),
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
Repeat,
|
||||
}
|
||||
|
||||
impl<'a> EncodeInput<'a> {
|
||||
|
||||
@@ -20,17 +20,6 @@ use std::{ptr, slice};
|
||||
generate_call_macro!(call_vpx, false);
|
||||
generate_call_ptr_macro!(call_vpx_ptr);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VpxNoOutput;
|
||||
|
||||
impl std::fmt::Display for VpxNoOutput {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("no valid frame")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VpxNoOutput {}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VpxVideoCodecId {
|
||||
VP8,
|
||||
@@ -198,7 +187,7 @@ impl EncoderApi for VpxEncoder {
|
||||
if frames.len() > 0 {
|
||||
Ok(VpxEncoder::create_video_frame(self.id, frames))
|
||||
} else {
|
||||
Err(VpxNoOutput.into())
|
||||
Err(anyhow!("no valid frame"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,8 @@ use hbb_common::{
|
||||
bytes::Bytes,
|
||||
log, ResultType,
|
||||
};
|
||||
pub use hwcodec::common::Driver;
|
||||
use hwcodec::{
|
||||
common::{DataFormat, MAX_GOP},
|
||||
common::{DataFormat, Driver, MAX_GOP},
|
||||
vram::{
|
||||
decode::{self, DecodeFrame, Decoder},
|
||||
encode::{self, EncodeFrame, Encoder},
|
||||
@@ -25,9 +24,6 @@ use hwcodec::{
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod repeat_tests;
|
||||
|
||||
// https://www.reddit.com/r/buildapc/comments/d2m4ny/two_graphics_cards_two_monitors/
|
||||
// https://www.reddit.com/r/techsupport/comments/t2v9u6/dual_monitor_setup_with_dual_gpu/
|
||||
// https://cybersided.com/two-monitors-two-gpus/
|
||||
@@ -52,6 +48,8 @@ pub struct VRamEncoder {
|
||||
pub format: DataFormat,
|
||||
ctx: EncodeContext,
|
||||
bitrate: u32,
|
||||
last_frame_len: usize,
|
||||
same_bad_len_counter: usize,
|
||||
}
|
||||
|
||||
impl EncoderApi for VRamEncoder {
|
||||
@@ -85,6 +83,8 @@ impl EncoderApi for VRamEncoder {
|
||||
ctx,
|
||||
format: config.feature.data_format,
|
||||
bitrate,
|
||||
last_frame_len: 0,
|
||||
same_bad_len_counter: 0,
|
||||
}),
|
||||
Err(_) => Err(anyhow!(format!("Failed to create encoder"))),
|
||||
}
|
||||
@@ -98,15 +98,7 @@ impl EncoderApi for VRamEncoder {
|
||||
frame: EncodeInput,
|
||||
ms: i64,
|
||||
) -> ResultType<base::message_proto::VideoFrame> {
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
let repeated = matches!(&frame, EncodeInput::Repeat);
|
||||
#[cfg(not(all(windows, feature = "vram")))]
|
||||
let repeated = false;
|
||||
let (texture, rotation) = if repeated {
|
||||
(std::ptr::null_mut(), 0)
|
||||
} else {
|
||||
frame.texture()?
|
||||
};
|
||||
let (texture, rotation) = frame.texture()?;
|
||||
if rotation != 0 {
|
||||
// to-do: support rotation
|
||||
// Both the encoder and display(w,h) information need to be changed.
|
||||
@@ -114,12 +106,10 @@ impl EncoderApi for VRamEncoder {
|
||||
}
|
||||
let mut vf = VideoFrame::new();
|
||||
let mut frames = Vec::new();
|
||||
let result = if repeated {
|
||||
self.encode_repeat(ms)
|
||||
} else {
|
||||
self.encode(texture, ms)
|
||||
};
|
||||
for frame in result.with_context(|| "Failed to encode")? {
|
||||
for frame in self
|
||||
.encode(texture, ms)
|
||||
.with_context(|| "Failed to encode")?
|
||||
{
|
||||
frames.push(EncodedVideoFrame {
|
||||
data: Bytes::from(frame.data),
|
||||
pts: frame.pts,
|
||||
@@ -127,10 +117,29 @@ impl EncoderApi for VRamEncoder {
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if repeated && frames.is_empty() {
|
||||
return Ok(vf);
|
||||
}
|
||||
if frames.len() > 0 {
|
||||
// This kind of problem is occurred after a period of time when using the AMD SDK,
|
||||
// the encoding length is fixed at about 40, and the picture is still
|
||||
const MIN_BAD_LEN: usize = 100;
|
||||
const MAX_BAD_COUNTER: usize = 30;
|
||||
let this_frame_len = frames[0].data.len();
|
||||
if self.ctx.f.driver == Driver::AMF
|
||||
&& this_frame_len < MIN_BAD_LEN
|
||||
&& this_frame_len == self.last_frame_len
|
||||
{
|
||||
self.same_bad_len_counter += 1;
|
||||
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
|
||||
log::info!(
|
||||
"{} times encoding len is {}, switch",
|
||||
self.same_bad_len_counter,
|
||||
self.last_frame_len
|
||||
);
|
||||
bail!(crate::codec::ENCODE_NEED_SWITCH);
|
||||
}
|
||||
} else {
|
||||
self.same_bad_len_counter = 0;
|
||||
}
|
||||
self.last_frame_len = this_frame_len;
|
||||
let frames = EncodedVideoFrames {
|
||||
frames: frames.into(),
|
||||
..Default::default()
|
||||
@@ -235,7 +244,6 @@ impl VRamEncoder {
|
||||
let v: Vec<_> = crate::hwcodec::HwCodecConfig::get()
|
||||
.vram_encode
|
||||
.drain(..)
|
||||
.filter(|c| c.driver == Driver::FFMPEG)
|
||||
.filter(|c| c.data_format == data_format)
|
||||
.collect();
|
||||
if crate::hwcodec::HwRamEncoder::try_get(format).is_some() {
|
||||
@@ -266,21 +274,14 @@ impl VRamEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&mut self,
|
||||
texture: *mut c_void,
|
||||
ms: i64,
|
||||
) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
|
||||
pub fn encode(&mut self, texture: *mut c_void, ms: i64) -> ResultType<Vec<EncodeFrame>> {
|
||||
match self.encoder.encode(texture, ms) {
|
||||
Ok(frames) => Ok(frames.drain(..)),
|
||||
Err(code) => Err(anyhow!("VRAM encode failed: {}", code)),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_repeat(&mut self, ms: i64) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
|
||||
match self.encoder.encode_repeat(ms) {
|
||||
Ok(frames) => Ok(frames.drain(..)),
|
||||
Err(code) => Err(anyhow!("VRAM repeat encode failed: {}", code)),
|
||||
Ok(v) => {
|
||||
let mut data = Vec::<EncodeFrame>::new();
|
||||
data.append(v);
|
||||
Ok(data)
|
||||
}
|
||||
Err(_) => Ok(Vec::<EncodeFrame>::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,7 +340,6 @@ impl VRamDecoder {
|
||||
crate::hwcodec::HwCodecConfig::get()
|
||||
.vram_decode
|
||||
.drain(..)
|
||||
.filter(|c| c.driver == Driver::FFMPEG)
|
||||
.filter(|c| c.data_format == data_format && c.luid == luid && luid != 0)
|
||||
.collect()
|
||||
}
|
||||
@@ -350,10 +350,8 @@ impl VRamDecoder {
|
||||
}
|
||||
let v = crate::hwcodec::HwCodecConfig::get().vram_decode;
|
||||
(
|
||||
v.iter()
|
||||
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H264),
|
||||
v.iter()
|
||||
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H265),
|
||||
v.iter().any(|d| d.data_format == DataFormat::H264),
|
||||
v.iter().any(|d| d.data_format == DataFormat::H265),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
use super::VRamEncoder;
|
||||
use crate::{codec::EncoderApi, EncodeInput};
|
||||
use base::message_proto::{video_frame, VideoFrame};
|
||||
use hwcodec::{
|
||||
common::{DataFormat, Driver, MAX_GOP},
|
||||
ffmpeg::AVHWDeviceType,
|
||||
ffmpeg_ram::decode::{DecodeContext, Decoder},
|
||||
vram::{encode::Encoder, DynamicContext, EncodeContext, FeatureContext},
|
||||
};
|
||||
use std::{mem, ptr};
|
||||
use winapi::{
|
||||
shared::{
|
||||
dxgi::{CreateDXGIFactory1, IDXGIFactory1},
|
||||
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
dxgitype::DXGI_SAMPLE_DESC,
|
||||
winerror::DXGI_ERROR_NOT_FOUND,
|
||||
},
|
||||
um::{d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown},
|
||||
Interface,
|
||||
};
|
||||
|
||||
struct Com<T>(*mut T);
|
||||
|
||||
impl<T> Drop for Com<T> {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe { (*(self.0 as *mut IUnknown)).Release() };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn texture(
|
||||
device: *mut ID3D11Device,
|
||||
width: u32,
|
||||
height: u32,
|
||||
shade: u8,
|
||||
) -> Com<ID3D11Texture2D> {
|
||||
let pixels = pixels(width, height, shade);
|
||||
let desc = D3D11_TEXTURE2D_DESC {
|
||||
Width: width,
|
||||
Height: height,
|
||||
MipLevels: 1,
|
||||
ArraySize: 1,
|
||||
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Usage: D3D11_USAGE_DEFAULT,
|
||||
BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
|
||||
CPUAccessFlags: 0,
|
||||
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
|
||||
};
|
||||
let data = D3D11_SUBRESOURCE_DATA {
|
||||
pSysMem: pixels.as_ptr() as _,
|
||||
SysMemPitch: width * 4,
|
||||
SysMemSlicePitch: 0,
|
||||
};
|
||||
let mut raw = ptr::null_mut();
|
||||
assert_eq!((*device).CreateTexture2D(&desc, &data, &mut raw), 0);
|
||||
Com(raw)
|
||||
}
|
||||
|
||||
fn pixels(width: u32, height: u32, shade: u8) -> Vec<u8> {
|
||||
[shade, shade, shade, 255].repeat((width * height) as usize)
|
||||
}
|
||||
|
||||
fn check_picture(
|
||||
decoder: &mut Decoder,
|
||||
frame: VideoFrame,
|
||||
width: u32,
|
||||
height: u32,
|
||||
bright: bool,
|
||||
pts: i64,
|
||||
) {
|
||||
let frames = match frame.union.unwrap() {
|
||||
video_frame::Union::H264s(frames) | video_frame::Union::H265s(frames) => frames,
|
||||
_ => panic!("unexpected codec"),
|
||||
};
|
||||
let mut decoded = 0;
|
||||
for packet in frames.frames {
|
||||
assert_eq!(packet.pts, pts);
|
||||
for picture in decoder.decode(&packet.data).unwrap() {
|
||||
assert_eq!((picture.width, picture.height), (width as _, height as _));
|
||||
let center = (height as usize / 2) * picture.linesize[0] as usize + width as usize / 2;
|
||||
let y = picture.data[0][center];
|
||||
assert!(
|
||||
if bright { y > 160 } else { y < 90 },
|
||||
"stale or overwritten pixels: expected bright={}, got Y={}",
|
||||
bright,
|
||||
y
|
||||
);
|
||||
decoded += 1;
|
||||
}
|
||||
}
|
||||
assert!(decoded > 0, "encoder output did not decode to a picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires hardware H.264/H.265 encoders; run explicitly on GPU hosts"]
|
||||
fn hardware_repeats_own_pixels_and_reset_on_recreation() {
|
||||
unsafe {
|
||||
let mut raw_factory = ptr::null_mut();
|
||||
assert_eq!(
|
||||
CreateDXGIFactory1(&IDXGIFactory1::uuidof(), &mut raw_factory),
|
||||
0
|
||||
);
|
||||
let factory = Com(raw_factory as *mut IDXGIFactory1);
|
||||
let mut tested = 0;
|
||||
for index in 0.. {
|
||||
let mut raw_adapter = ptr::null_mut();
|
||||
let result = (*factory.0).EnumAdapters1(index, &mut raw_adapter);
|
||||
if result == DXGI_ERROR_NOT_FOUND {
|
||||
break;
|
||||
}
|
||||
assert_eq!(result, 0);
|
||||
let adapter = Com(raw_adapter);
|
||||
let mut desc = mem::zeroed();
|
||||
assert_eq!((*adapter.0).GetDesc1(&mut desc), 0);
|
||||
let vendor = match desc.VendorId {
|
||||
0x10de => Driver::NV,
|
||||
0x1002 => Driver::AMF,
|
||||
0x8086 => Driver::MFX,
|
||||
_ => continue,
|
||||
};
|
||||
let luid = ((desc.AdapterLuid.HighPart as i64) << 32) | desc.AdapterLuid.LowPart as i64;
|
||||
let mut raw_device = ptr::null_mut();
|
||||
let mut raw_context = ptr::null_mut();
|
||||
assert_eq!(
|
||||
D3D11CreateDevice(
|
||||
adapter.0 as _,
|
||||
D3D_DRIVER_TYPE_UNKNOWN,
|
||||
ptr::null_mut(),
|
||||
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
|
||||
ptr::null(),
|
||||
0,
|
||||
D3D11_SDK_VERSION,
|
||||
&mut raw_device,
|
||||
ptr::null_mut(),
|
||||
&mut raw_context,
|
||||
),
|
||||
0
|
||||
);
|
||||
let device = Com(raw_device);
|
||||
let context = Com(raw_context);
|
||||
for driver in [Driver::FFMPEG, vendor.clone()] {
|
||||
for format in [DataFormat::H264, DataFormat::H265] {
|
||||
for (width, height) in [(320, 240), (640, 360)] {
|
||||
let ctx = EncodeContext {
|
||||
f: FeatureContext {
|
||||
driver: driver.clone(),
|
||||
vendor: vendor.clone(),
|
||||
luid,
|
||||
data_format: format,
|
||||
},
|
||||
d: DynamicContext {
|
||||
device: Some(device.0 as _),
|
||||
width: width as _,
|
||||
height: height as _,
|
||||
kbitrate: 1000,
|
||||
framerate: 30,
|
||||
gop: MAX_GOP as _,
|
||||
},
|
||||
};
|
||||
let native = match Encoder::new(ctx.clone()) {
|
||||
Ok(encoder) => encoder,
|
||||
Err(()) => {
|
||||
eprintln!(
|
||||
"SKIP unavailable {:?} {:?} {:?} adapter={luid:#x}",
|
||||
vendor, driver, format
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut encoder = VRamEncoder {
|
||||
encoder: native,
|
||||
format,
|
||||
ctx,
|
||||
bitrate: 1000,
|
||||
};
|
||||
assert!(encoder.encode_to_message(EncodeInput::Repeat, 0).is_err());
|
||||
assert!(encoder
|
||||
.encode_to_message(EncodeInput::Texture((ptr::null_mut(), 0)), 0)
|
||||
.is_err());
|
||||
let mut decoder = Decoder::new(DecodeContext {
|
||||
name: if format == DataFormat::H264 {
|
||||
"h264"
|
||||
} else {
|
||||
"hevc"
|
||||
}
|
||||
.into(),
|
||||
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
|
||||
thread_count: 1,
|
||||
})
|
||||
.unwrap();
|
||||
let source = texture(device.0, width, height, 32);
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 0)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, false, 0);
|
||||
|
||||
// Overwrite and release the capture resource before any repeats.
|
||||
let overwritten = pixels(width, height, 224);
|
||||
(*context.0).UpdateSubresource(
|
||||
source.0 as _,
|
||||
0,
|
||||
ptr::null(),
|
||||
overwritten.as_ptr() as _,
|
||||
width * 4,
|
||||
0,
|
||||
);
|
||||
(*context.0).Flush();
|
||||
drop(source);
|
||||
for count in 1..=100 {
|
||||
let pts = count * 100;
|
||||
let frame =
|
||||
encoder.encode_to_message(EncodeInput::Repeat, pts).unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, false, pts);
|
||||
}
|
||||
|
||||
let source = texture(device.0, width, height, 224);
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 10100)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, true, 10100);
|
||||
drop(source);
|
||||
encoder.encoder.set_bitrate(1500).unwrap();
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Repeat, 10200)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, true, 10200);
|
||||
eprintln!(
|
||||
"PASS {:?} {:?} {:?} {width}x{height} adapter={luid:#x}",
|
||||
vendor, driver, format
|
||||
);
|
||||
tested += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(tested > 0, "no hardware encoders were tested");
|
||||
eprintln!("Validated {tested} encoder/codec/resolution combinations");
|
||||
}
|
||||
}
|
||||
@@ -12,12 +12,7 @@ use super::{Display, Rect, Server};
|
||||
|
||||
pub struct DisplayIter {
|
||||
outer: xcb_screen_iterator_t,
|
||||
// The monitor iterator points into the reply, so the reply is freed only when moving on.
|
||||
inner: Option<(
|
||||
xcb_randr_monitor_info_iterator_t,
|
||||
xcb_window_t,
|
||||
*mut xcb_randr_get_monitors_reply_t,
|
||||
)>,
|
||||
inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,
|
||||
server: Rc<Server>,
|
||||
}
|
||||
|
||||
@@ -35,11 +30,7 @@ impl DisplayIter {
|
||||
fn next_screen(
|
||||
outer: &mut xcb_screen_iterator_t,
|
||||
server: &Server,
|
||||
) -> Option<(
|
||||
xcb_randr_monitor_info_iterator_t,
|
||||
xcb_window_t,
|
||||
*mut xcb_randr_get_monitors_reply_t,
|
||||
)> {
|
||||
) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {
|
||||
if outer.rem == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -57,17 +48,10 @@ impl DisplayIter {
|
||||
|
||||
let inner = xcb_randr_get_monitors_monitors_iterator(response);
|
||||
|
||||
libc::free(response as *mut _);
|
||||
xcb_screen_next(outer);
|
||||
|
||||
Some((inner, root, response))
|
||||
}
|
||||
}
|
||||
|
||||
fn free_reply(&mut self) {
|
||||
if let Some((_, _, response)) = self.inner.take() {
|
||||
unsafe {
|
||||
libc::free(response as *mut _);
|
||||
}
|
||||
Some((inner, root))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,7 +61,7 @@ impl Iterator for DisplayIter {
|
||||
|
||||
fn next(&mut self) -> Option<Display> {
|
||||
loop {
|
||||
if let Some((ref mut inner, root, _)) = self.inner {
|
||||
if let Some((ref mut inner, root)) = self.inner {
|
||||
// If there is something in the current screen, return that.
|
||||
if inner.rem != 0 {
|
||||
unsafe {
|
||||
@@ -108,18 +92,11 @@ impl Iterator for DisplayIter {
|
||||
}
|
||||
|
||||
// The current screen was empty, so try the next screen.
|
||||
self.free_reply();
|
||||
self.inner = Self::next_screen(&mut self.outer, &self.server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DisplayIter {
|
||||
fn drop(&mut self) {
|
||||
self.free_reply();
|
||||
}
|
||||
}
|
||||
|
||||
fn get_atom_name(conn: *mut xcb_connection_t, atom: xcb_atom_t) -> String {
|
||||
let empty = "".to_owned();
|
||||
if atom == 0 {
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
diff --git a/libavcodec/qsvenc.c b/libavcodec/qsvenc.c
|
||||
--- a/libavcodec/qsvenc.c
|
||||
+++ b/libavcodec/qsvenc.c
|
||||
@@ -43,6 +43,9 @@
|
||||
#include "qsv_internal.h"
|
||||
#include "qsvenc.h"
|
||||
#include "refstruct.h"
|
||||
+
|
||||
+#define QSV_MAX_ENCODE_RETRIES 100
|
||||
+#define QSV_SYNC_TIMEOUT_US 2000000
|
||||
|
||||
struct profile_names {
|
||||
mfxU16 profile;
|
||||
@@ -2468,6 +2471,7 @@
|
||||
QSVFrame *qsv_frame = NULL;
|
||||
mfxEncodeCtrl* enc_ctrl = NULL;
|
||||
int ret;
|
||||
+ int retries = 0;
|
||||
|
||||
if (frame) {
|
||||
ret = submit_frame(q, frame, &qsv_frame);
|
||||
@@ -2538,6 +2542,18 @@
|
||||
|
||||
do {
|
||||
ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, pkt.bs, pkt.sync);
|
||||
+ if ((ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION) &&
|
||||
+ retries++ >= QSV_MAX_ENCODE_RETRIES) {
|
||||
+ av_log(avctx, AV_LOG_ERROR, "QSV encoder submission retry limit exceeded\n");
|
||||
+ ret = AVERROR_EXTERNAL;
|
||||
+ goto free;
|
||||
+ }
|
||||
+#ifdef _WIN32
|
||||
+ // Sub-millisecond waits become Sleep(0) on Windows.
|
||||
+ if (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION)
|
||||
+ av_usleep(1000);
|
||||
+#else
|
||||
if (ret == MFX_WRN_DEVICE_BUSY)
|
||||
av_usleep(500);
|
||||
+#endif
|
||||
} while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
|
||||
@@ -2656,12 +2672,23 @@
|
||||
mfxExtAVCEncodedFrameInfo *enc_info;
|
||||
mfxExtBuffer **enc_buf;
|
||||
enum AVPictureType pict_type;
|
||||
-
|
||||
- av_fifo_read(q->async_fifo, &qpkt, 1);
|
||||
+ int64_t sync_deadline = av_gettime_relative() + QSV_SYNC_TIMEOUT_US;
|
||||
+
|
||||
+ // The SDK may still use these buffers after a synchronization timeout.
|
||||
+ av_fifo_peek(q->async_fifo, &qpkt, 1, 0);
|
||||
|
||||
do {
|
||||
- ret = MFXVideoCORE_SyncOperation(q->session, *qpkt.sync, 1000);
|
||||
+ int64_t remaining = sync_deadline - av_gettime_relative();
|
||||
+ if (remaining <= 0) {
|
||||
+ av_log(avctx, AV_LOG_ERROR, "QSV encoder synchronization timed out\n");
|
||||
+ return AVERROR_EXTERNAL;
|
||||
+ }
|
||||
+ ret = MFXVideoCORE_SyncOperation(q->session, *qpkt.sync,
|
||||
+ FFMIN(1000, (remaining + 999) / 1000));
|
||||
+ if (ret == MFX_WRN_IN_EXECUTION)
|
||||
+ av_usleep(1000);
|
||||
} while (ret == MFX_WRN_IN_EXECUTION);
|
||||
+ av_fifo_drain2(q->async_fifo, 1);
|
||||
|
||||
qpkt.pkt.dts = av_rescale_q(qpkt.bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
|
||||
qpkt.pkt.pts = av_rescale_q(qpkt.bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
|
||||
@@ -1,64 +0,0 @@
|
||||
diff --git a/libavcodec/qsvenc.c b/libavcodec/qsvenc.c
|
||||
--- a/libavcodec/qsvenc.c
|
||||
+++ b/libavcodec/qsvenc.c
|
||||
@@ -1419,6 +1419,18 @@
|
||||
return 0;
|
||||
}
|
||||
|
||||
+static int qsv_update_packet_size(QSVEncContext *q, const mfxInfoMFX *mfx)
|
||||
+{
|
||||
+ // Intel documents a larger buffer for complex CQP frames.
|
||||
+ // https://github.com/Intel-Media-SDK/MediaSDK/blob/master/doc/mediasdk_release_notes.md
|
||||
+ int64_t packet_size = (int64_t)mfx->BufferSizeInKB * mfx->BRCParamMultiplier * 1000 * 4;
|
||||
+
|
||||
+ if (packet_size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
|
||||
+ return AVERROR(ENOMEM);
|
||||
+ q->packet_size = FFMAX(q->packet_size, packet_size);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
|
||||
{
|
||||
AVCPBProperties *cpb_props;
|
||||
@@ -1508,7 +1520,13 @@
|
||||
return ff_qsv_print_error(avctx, ret,
|
||||
"Error calling GetVideoParam");
|
||||
|
||||
- q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
|
||||
+ if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
|
||||
+ ret = qsv_update_packet_size(q, &q->param.mfx);
|
||||
+ if (ret < 0)
|
||||
+ return ret;
|
||||
+ } else {
|
||||
+ q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
|
||||
+ }
|
||||
|
||||
if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)
|
||||
|| (q->hevc_vps && !extradata_vps.VPSBufSize)
|
||||
@@ -2650,6 +2668,17 @@
|
||||
if (ret < 0)
|
||||
return ff_qsv_print_error(avctx, ret, "Error during resetting");
|
||||
|
||||
+ if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
|
||||
+ mfxVideoParam param = { 0 };
|
||||
+
|
||||
+ ret = MFXVideoENCODE_GetVideoParam(q->session, ¶m);
|
||||
+ if (ret < 0)
|
||||
+ return ff_qsv_print_error(avctx, ret, "Error querying parameters after reset");
|
||||
+ ret = qsv_update_packet_size(q, ¶m.mfx);
|
||||
+ if (ret < 0)
|
||||
+ return ret;
|
||||
+ }
|
||||
+
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2688,6 +2717,8 @@
|
||||
if (ret == MFX_WRN_IN_EXECUTION)
|
||||
av_usleep(1000);
|
||||
} while (ret == MFX_WRN_IN_EXECUTION);
|
||||
+ if (ret < 0)
|
||||
+ return ff_qsv_print_error(avctx, ret, "Error synchronizing encoded frame");
|
||||
av_fifo_drain2(q->async_fifo, 1);
|
||||
|
||||
qpkt.pkt.dts = av_rescale_q(qpkt.bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
|
||||
@@ -1,89 +0,0 @@
|
||||
From: Martin Storsjö
|
||||
Subject: movenc: Make the hybrid_fragmented mode more robust
|
||||
Source: https://github.com/FFmpeg/FFmpeg/commit/36896af64a9ecf6835758186e7161a2e954c364d
|
||||
|
||||
movenc: Make the hybrid_fragmented mode more robust
|
||||
|
||||
Write the moov tag at the end first, before overwriting the mdat size
|
||||
at the start of the file.
|
||||
|
||||
In case writing the final moov box fails (e.g. due to being out
|
||||
of disk), we haven't broken the initial moov box yet.
|
||||
|
||||
Thus if writing stops between these steps, we could end up with
|
||||
a file with two moov boxes - which arguably is more feasible to
|
||||
recover from, than from a file with no moov boxes at all.
|
||||
|
||||
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
|
||||
--- a/libavformat/movenc.c
|
||||
+++ b/libavformat/movenc.c
|
||||
@@ -8546,6 +8546,28 @@ static int shift_data(AVFormatContext *s)
|
||||
return ff_format_shift_data(s, mov->reserved_header_pos, moov_size);
|
||||
}
|
||||
|
||||
+static void mov_write_mdat_size(AVFormatContext *s)
|
||||
+{
|
||||
+ MOVMuxContext *mov = s->priv_data;
|
||||
+ AVIOContext *pb = s->pb;
|
||||
+
|
||||
+ /* Write size of mdat tag */
|
||||
+ if (mov->mdat_size + 8 <= UINT32_MAX) {
|
||||
+ avio_seek(pb, mov->mdat_pos, SEEK_SET);
|
||||
+ avio_wb32(pb, mov->mdat_size + 8);
|
||||
+ if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED)
|
||||
+ ffio_wfourcc(pb, "mdat"); // overwrite the original moov into a mdat
|
||||
+ } else {
|
||||
+ /* overwrite 'wide' placeholder atom */
|
||||
+ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
|
||||
+ /* special value: real atom size will be 64 bit value after
|
||||
+ * tag field */
|
||||
+ avio_wb32(pb, 1);
|
||||
+ ffio_wfourcc(pb, "mdat");
|
||||
+ avio_wb64(pb, mov->mdat_size + 16);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
static int mov_write_trailer(AVFormatContext *s)
|
||||
{
|
||||
MOVMuxContext *mov = s->priv_data;
|
||||
@@ -8605,21 +8627,9 @@ static int mov_write_trailer(AVFormatContext *s)
|
||||
|
||||
moov_pos = avio_tell(pb);
|
||||
|
||||
- /* Write size of mdat tag */
|
||||
- if (mov->mdat_size + 8 <= UINT32_MAX) {
|
||||
- avio_seek(pb, mov->mdat_pos, SEEK_SET);
|
||||
- avio_wb32(pb, mov->mdat_size + 8);
|
||||
- if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED)
|
||||
- ffio_wfourcc(pb, "mdat"); // overwrite the original moov into a mdat
|
||||
- } else {
|
||||
- /* overwrite 'wide' placeholder atom */
|
||||
- avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
|
||||
- /* special value: real atom size will be 64 bit value after
|
||||
- * tag field */
|
||||
- avio_wb32(pb, 1);
|
||||
- ffio_wfourcc(pb, "mdat");
|
||||
- avio_wb64(pb, mov->mdat_size + 16);
|
||||
- }
|
||||
+ if (!(mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED))
|
||||
+ mov_write_mdat_size(s);
|
||||
+
|
||||
avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
|
||||
|
||||
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
|
||||
@@ -8647,6 +8657,15 @@ static int mov_write_trailer(AVFormatContext *s)
|
||||
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
|
||||
return res;
|
||||
}
|
||||
+
|
||||
+ if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED) {
|
||||
+ // With hybrid fragmentation, only write the mdat size (hiding
|
||||
+ // the original moov and all the fragments within the mdat)
|
||||
+ // after we've successfully written the complete moov, to avoid
|
||||
+ // risk for an unreadable file if writing the final moov fails.
|
||||
+ mov_write_mdat_size(s);
|
||||
+ }
|
||||
+
|
||||
res = 0;
|
||||
} else {
|
||||
mov_auto_flush_fragment(s, 1);
|
||||
@@ -30,9 +30,6 @@ vcpkg_from_github(
|
||||
patch/0010.disable-loading-DLLs-from-app-dir.patch
|
||||
patch/0011-android-mediacodec-encode-align-64.patch
|
||||
patch/0012-fix-macos-big-sur-CVBufferCopyAttachments.patch
|
||||
patch/0013-fix-qsv-encode-timeouts.patch
|
||||
patch/0014-fix-qsv-encode-buffer.patch
|
||||
patch/0015-fix-hybrid-mp4-finalization.patch
|
||||
)
|
||||
|
||||
if(SOURCE_PATH MATCHES " ")
|
||||
|
||||
+2
-28
@@ -267,13 +267,7 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
|
||||
}
|
||||
}
|
||||
match others_err.take() {
|
||||
// Report one error, as `select_ok` does: the UI matches and translates
|
||||
// the text whole (e.g. the offline auto-retry), and both legs often
|
||||
// carry the same rendezvous refusal anyway.
|
||||
Some(oe) => {
|
||||
log::warn!("fallback leg also failed: {}", oe);
|
||||
return Err(e);
|
||||
}
|
||||
Some(oe) => bail!("WebRTC failed: {}; fallback failed: {}", e, oe),
|
||||
None if others_fut.is_none() => bail!("WebRTC failed: {}", e),
|
||||
None => webrtc_err = Some(e),
|
||||
}
|
||||
@@ -314,10 +308,7 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
|
||||
// it before failing the connection.
|
||||
Some(we) => match held.take() {
|
||||
Some(conn) => return Ok(conn),
|
||||
None => {
|
||||
log::warn!("WebRTC leg also failed: {}", we);
|
||||
return Err(e);
|
||||
}
|
||||
None => bail!("WebRTC failed: {}; fallback failed: {}", we, e),
|
||||
},
|
||||
None if webrtc_fut.is_none() => match held.take() {
|
||||
Some(conn) => return Ok(conn),
|
||||
@@ -5718,23 +5709,6 @@ mod webrtc_race_tests {
|
||||
assert_eq!(got, "ipv6");
|
||||
assert!(start.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// Both legs get the same rendezvous refusal; the UI needs the text verbatim, e.g. the
|
||||
// offline auto-retry matches it whole. Either leg may fail last.
|
||||
#[tokio::test]
|
||||
async fn same_failure_on_both_legs_reported_once() {
|
||||
for (webrtc_ms, fallback_ms) in [(10, 20), (20, 10)] {
|
||||
let err = race_transports_prefer_webrtc(
|
||||
err_after(webrtc_ms, "Remote desktop is offline"),
|
||||
vec![err_after(fallback_ms, "Remote desktop is offline")],
|
||||
60_000,
|
||||
NOT_P2P,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.to_string(), "Remote desktop is offline");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+13
-41
@@ -809,16 +809,7 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
if is_remote {
|
||||
log::debug!("New job {}, write to {} from remote {}", id, to, path);
|
||||
let to = match r#type {
|
||||
fs::JobType::Generic => {
|
||||
if let Err(err) = fs::download::validate_download_name(
|
||||
&path,
|
||||
self.handler.peer_platform() == "Windows",
|
||||
) {
|
||||
self.handle_job_status(id, -1, Some(err.to_string()));
|
||||
return true;
|
||||
}
|
||||
fs::DataSource::FilePath(PathBuf::from(&to))
|
||||
}
|
||||
fs::JobType::Generic => fs::DataSource::FilePath(PathBuf::from(&to)),
|
||||
fs::JobType::Printer => {
|
||||
fs::DataSource::MemoryCursor(std::io::Cursor::new(Vec::new()))
|
||||
}
|
||||
@@ -1791,15 +1782,6 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
fs::transform_windows_path(&mut entries);
|
||||
}
|
||||
}
|
||||
if fd.id <= 0 {
|
||||
if let Err(err) = fs::download::validate_listing(
|
||||
&entries,
|
||||
self.handler.peer_platform() == "Windows",
|
||||
) {
|
||||
self.handle_job_status(fd.id, -1, Some(err.to_string()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// We cannot call cancel_transfer_job/handle_job_status while holding
|
||||
// a mutable borrow from fs::get_job(&mut self.write_jobs), so defer
|
||||
// the error handling until after the borrow scope ends.
|
||||
@@ -1895,7 +1877,11 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
crate::is_support_file_transfer_resume_num(
|
||||
peer_ver,
|
||||
);
|
||||
match job.download_digest(is_support_resume, &digest) {
|
||||
match fs::is_write_need_confirmation(
|
||||
is_support_resume && job.is_resume,
|
||||
&write_path,
|
||||
&digest,
|
||||
) {
|
||||
Ok(res) => match res {
|
||||
DigestCheckResult::IsSame => {
|
||||
let req = FileTransferSendConfirmRequest {
|
||||
@@ -1952,19 +1938,13 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(0)),
|
||||
..Default::default()
|
||||
};
|
||||
// This did not approve replacing an existing local file.
|
||||
job.confirm(&req).await;
|
||||
let msg = new_send_confirm(req);
|
||||
allow_err!(peer.send(&msg).await);
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
self.cancel_transfer_job(digest.id, peer).await;
|
||||
self.handle_job_status(
|
||||
digest.id,
|
||||
-1,
|
||||
Some(err.to_string()),
|
||||
);
|
||||
return true;
|
||||
println!("error receiving digest: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1973,30 +1953,22 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
}
|
||||
}
|
||||
Some(file_response::Union::Block(block)) => {
|
||||
let id = block.id;
|
||||
let mut write_error = None;
|
||||
if let Some(job) = fs::get_job(block.id, &mut self.write_jobs) {
|
||||
let result = job.write(block).await;
|
||||
if let Err(_err) = job.write(block).await {
|
||||
// to-do: add "skip" for writing job
|
||||
}
|
||||
if job.r#type == fs::JobType::Generic {
|
||||
write_error = result.err().map(|err| err.to_string());
|
||||
self.update_jobs_status();
|
||||
}
|
||||
}
|
||||
if let Some(err) = write_error {
|
||||
self.cancel_transfer_job(id, peer).await;
|
||||
self.handle_job_status(id, -1, Some(err));
|
||||
}
|
||||
}
|
||||
Some(file_response::Union::Done(d)) => {
|
||||
let mut err: Option<String> = None;
|
||||
let mut job_type = fs::JobType::Generic;
|
||||
let mut printer_data = None;
|
||||
if let Some(job) = fs::remove_job(d.id, &mut self.write_jobs) {
|
||||
err = job
|
||||
.finish_download()
|
||||
.err()
|
||||
.map(|err| err.to_string())
|
||||
.or_else(|| job.job_error());
|
||||
job.modify_time();
|
||||
err = job.job_error();
|
||||
job_type = job.r#type;
|
||||
printer_data = match job.get_buf_data().await {
|
||||
Ok(d) => d,
|
||||
|
||||
@@ -1251,11 +1251,6 @@ fn get_api_server_(api: String, custom: String) -> String {
|
||||
if !s0.is_empty() {
|
||||
let s = crate::increase_port(&s0, -2);
|
||||
if s == s0 {
|
||||
let s = if hbb_common::is_ipv6_str(&s) && !s.starts_with('[') {
|
||||
format!("[{s}]")
|
||||
} else {
|
||||
s
|
||||
};
|
||||
return format!("http://{}:{}", s, config::RENDEZVOUS_PORT - 2);
|
||||
} else {
|
||||
return format!("http://{}", s);
|
||||
@@ -3214,14 +3209,6 @@ mod tests {
|
||||
assert!(!is_public("https://rustdesk.com@evil.test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_api_server_from_bare_ipv6_rendezvous_server() {
|
||||
assert_eq!(
|
||||
get_api_server_("".to_owned(), "2001:db8::1".to_owned()),
|
||||
"http://[2001:db8::1]:21114"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_use_tcp_proxy_for_api_url() {
|
||||
assert!(should_use_tcp_proxy_for_api_url(
|
||||
|
||||
@@ -2763,16 +2763,6 @@ pub fn main_get_common(key: String) -> String {
|
||||
}
|
||||
|
||||
pub fn main_get_common_sync(key: String) -> SyncReturn<String> {
|
||||
if let Some(args) = key.strip_prefix("resolve-api-server:") {
|
||||
let response = match serde_json::from_str::<(String, String)>(args) {
|
||||
Ok((api, custom)) => serde_json::json!({"url": crate::get_api_server(api, custom)}),
|
||||
Err(err) => {
|
||||
log::trace!("Invalid API server preview arguments: {err}");
|
||||
serde_json::json!({"error": err.to_string()})
|
||||
}
|
||||
};
|
||||
return SyncReturn(response.to_string());
|
||||
}
|
||||
// Metadata verification performs blocking network requests. Keep this key on
|
||||
// the asynchronous FFI path to avoid blocking the calling Flutter isolate.
|
||||
if key.starts_with("verified-download-url-") {
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "“{}” 不能用作快捷键。"),
|
||||
("On", "开"),
|
||||
("Off", "关"),
|
||||
("api_server_connection_tip", "自定义服务器正在使用未加密的 HTTP。请联系管理员启用 HTTPS。"),
|
||||
("api_server_empty_tip", "API 服务器留空时,自定义服务器默认使用 HTTP。请联系管理员启用 HTTPS。"),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -288,7 +288,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-already-bound-to", "Already bound to"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Recording requires a physical keyboard. Soft keyboards are not supported."),
|
||||
("shortcut-key-not-supported", "\"{}\" can't be used as a shortcut."),
|
||||
("api_server_connection_tip", "Your custom server uses unencrypted HTTP. Contact your administrator to enable HTTPS."),
|
||||
("api_server_empty_tip", "With API Server empty, your custom server defaults to HTTP. Contact your administrator to enable HTTPS."),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+33
-33
@@ -780,38 +780,38 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk نتوانست مؤلفه GStreamer موردنیاز برای ضبط صفحه را بارگذاری کند ({})"),
|
||||
("Relay fallback delay in seconds", "تأخیر بازگشت به رله بر حسب ثانیه"),
|
||||
("relay-fallback-delay-tip", "یک اتصال رله که از قبل برقرار شده چقدر منتظر اتصال مستقیم WebRTC می ماند پیش از آنکه به جای آن استفاده شود. آن را افزایش دهید تا به اتصال مستقیم کند فرصت بیشتری داده شود؛ کاهش دهید تا در شبکه هایی که اتصال مستقیم ممکن نیست، زودتر به رله بازگردد. برای مقدار پیش فرض 2.5 ثانیه خالی بگذارید."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "برای شروع تماس صوتی، گزینه «ضبط صدا» را در صفحه «اشتراکگذاری صفحه» فعال کنید."),
|
||||
("Keyboard shortcuts", "میانبرهای صفحه کلید"),
|
||||
("Configure shortcuts...", "پیکربندی میانبرها..."),
|
||||
("Enable keyboard shortcuts in remote session", "فعالسازی میانبرهای صفحه کلید در جلسه راه دور"),
|
||||
("shortcut-page-description", "میانبرهای صفحه کلید را برای کارهای رایج در جلسه راه دور تنظیم کنید."),
|
||||
("shortcut-passthrough-tip", "با فعال بودن ارسال مستقیم، میانبرهای فعالشده به جای دستگاه محلی به دستگاه راه دور ارسال میشوند."),
|
||||
("Pass-through to remote", "ارسال مستقیم به راه دور"),
|
||||
("Reset to defaults", "بازنشانی به پیشفرض"),
|
||||
("shortcut-reset-confirm-tip", "همه میانبرها به مقادیر پیشفرض بازنشانی شوند؟"),
|
||||
("Monitor", "نمایشگر"),
|
||||
("Keyboard", "صفحه کلید"),
|
||||
("Toggle fullscreen", "تغییر حالت تمام صفحه"),
|
||||
("Switch to next display", "رفتن به نمایشگر بعدی"),
|
||||
("Switch to previous display", "رفتن به نمایشگر قبلی"),
|
||||
("Switch to next tab", "رفتن به زبانه بعدی"),
|
||||
("Switch to previous tab", "رفتن به زبانه قبلی"),
|
||||
("Toggle session recording", "تغییر وضعیت ضبط جلسه"),
|
||||
("Close tab", "بستن زبانه"),
|
||||
("Toggle toolbar", "نمایش/پنهان کردن نوار ابزار"),
|
||||
("Toggle input source", "تغییر منبع ورودی"),
|
||||
("Edit", "ویرایش"),
|
||||
("Save", "ذخیره"),
|
||||
("Set shortcut", "تنظیم میانبر"),
|
||||
("shortcut-recording-instruction", "کلیدهای میانبر مورد نظر را فشار دهید."),
|
||||
("shortcut-recording-press-keys-tip", "کلیدها را فشار دهید..."),
|
||||
("shortcut-must-include-modifiers", "میانبر باید شامل حداقل یک کلید تغییردهنده (Ctrl، Alt، Shift یا Meta) باشد."),
|
||||
("shortcut-already-bound-to", "این میانبر قبلاً به عملکرد دیگری اختصاص داده شده است."),
|
||||
("Replace", "جایگزینی"),
|
||||
("Valid", "معتبر"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "این میانبرها فقط با صفحه کلید فیزیکی متصل کار میکنند."),
|
||||
("shortcut-key-not-supported", "این کلید برای میانبر پشتیبانی نمیشود."),
|
||||
("On", "روشن"),
|
||||
("Off", "خاموش"),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", ""),
|
||||
("Keyboard shortcuts", ""),
|
||||
("Configure shortcuts...", ""),
|
||||
("Enable keyboard shortcuts in remote session", ""),
|
||||
("shortcut-page-description", ""),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", ""),
|
||||
("Reset to defaults", ""),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", ""),
|
||||
("Keyboard", ""),
|
||||
("Toggle fullscreen", ""),
|
||||
("Switch to next display", ""),
|
||||
("Switch to previous display", ""),
|
||||
("Switch to next tab", ""),
|
||||
("Switch to previous tab", ""),
|
||||
("Toggle session recording", ""),
|
||||
("Close tab", ""),
|
||||
("Toggle toolbar", ""),
|
||||
("Toggle input source", ""),
|
||||
("Edit", ""),
|
||||
("Save", ""),
|
||||
("Set shortcut", ""),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", ""),
|
||||
("shortcut-already-bound-to", ""),
|
||||
("Replace", ""),
|
||||
("Valid", ""),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+21
-23
@@ -69,7 +69,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Retry", "Coba lagi"),
|
||||
("OK", "Oke"),
|
||||
("Password Required", "Kata sandi tidak boleh kosong"),
|
||||
("Please enter your password", "Silakan masukkan kata sandi"),
|
||||
("Please enter your password", "Silahkan masukkan kata sandi"),
|
||||
("Remember password", "Ingat kata sandi"),
|
||||
("Wrong Password", "Kata sandi Salah"),
|
||||
("Do you want to enter again?", "Apakah kamu ingin mencoba lagi?"),
|
||||
@@ -78,7 +78,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Reset by the peer", "Direset oleh rekan"),
|
||||
("Connecting...", "Menghubungkan..."),
|
||||
("Connection in progress. Please wait.", "Koneksi sedang berlangsung. Mohon tunggu."),
|
||||
("Please try 1 minute later", "Silakan coba 1 menit lagi"),
|
||||
("Please try 1 minute later", "Silahkan coba 1 menit lagi"),
|
||||
("Login Error", "Kesalahan Login"),
|
||||
("Successful", "Berhasil"),
|
||||
("Connected, waiting for image...", "Terhubung, menunggu gambar..."),
|
||||
@@ -103,8 +103,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Empty Directory", "Folder Kosong"),
|
||||
("Not an empty directory", "Folder tidak kosong"),
|
||||
("Are you sure you want to delete this file?", "Apakah kamu yakin untuk menghapus file ini?"),
|
||||
("Are you sure you want to delete this empty directory?", "Apakah yakin untuk menghapus folder ini?"),
|
||||
("Are you sure you want to delete the file of this directory?", "Apakah yakin untuk menghapus file dan folder ini?"),
|
||||
("Are you sure you want to delete this empty directory?", "Apakah yakin yakin untuk menghapus folder ini?"),
|
||||
("Are you sure you want to delete the file of this directory?", "Apakah yakin yakin untuk menghapus file dan folder ini?"),
|
||||
("Do this for all conflicts", "Lakukan untuk semua konflik"),
|
||||
("This is irreversible!", "Ini tidak dapat diubah!"),
|
||||
("Deleting", "Menghapus"),
|
||||
@@ -135,7 +135,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Refresh", "Segarkan"),
|
||||
("ID does not exist", "ID tidak ada"),
|
||||
("Failed to connect to rendezvous server", "Gagal menghubungkan ke rendezvous server"),
|
||||
("Please try later", "Silakan coba lagi nanti"),
|
||||
("Please try later", "Silahkan coba lagi nanti"),
|
||||
("Remote desktop is offline", "Remote desktop offline"),
|
||||
("Key mismatch", "Ketidakcocokan kunci"),
|
||||
("Timeout", "Waktu habis"),
|
||||
@@ -150,14 +150,14 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Configure", "Konfigurasi"),
|
||||
("config_acc", "Agar bisa mengontrol Desktopmu dari jarak jauh, Kamu harus memberikan izin \"Aksesibilitas\" untuk RustDesk."),
|
||||
("config_screen", "Agar bisa mengakses Desktopmu dari jarak jauh, kamu harus memberikan izin \"Perekaman Layar\" untuk RustDesk."),
|
||||
("Installing ...", "Menginstal"),
|
||||
("Installing ...", "Menginstall"),
|
||||
("Install", "Instal"),
|
||||
("Installation", "Instalasi"),
|
||||
("Installation Path", "Direktori Instalasi"),
|
||||
("Create start menu shortcuts", "Buat pintasan start menu"),
|
||||
("Create desktop icon", "Buat ikon desktop"),
|
||||
("Create desktop icon", "Buat icon desktop"),
|
||||
("agreement_tip", "Dengan memulai proses instalasi, Kamu menerima perjanjian lisensi."),
|
||||
("Accept and Install", "Terima dan Instal"),
|
||||
("Accept and Install", "Terima dan Install"),
|
||||
("End-user license agreement", "Perjanjian lisensi pengguna"),
|
||||
("Generating ...", "Memproses..."),
|
||||
("Your installation is lower version.", "Kamu menggunakan versi instalasi yang lebih rendah."),
|
||||
@@ -171,7 +171,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Local Address", "Alamat lokal"),
|
||||
("Change Local Port", "Ubah Port Lokal"),
|
||||
("setup_server_tip", "Untuk koneksi yang lebih baik, silakan konfigurasi di server pribadi"),
|
||||
("Too short, at least 6 characters.", "Terlalu pendek, setidaknya 6 karakter."),
|
||||
("Too short, at least 6 characters.", "Terlalu pendek, setidaknya 6 karekter."),
|
||||
("The confirmation is not identical.", "Konfirmasi tidak identik."),
|
||||
("Permissions", "Perizinan"),
|
||||
("Accept", "Terima"),
|
||||
@@ -194,7 +194,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Create desktop shortcut", "Buat Pintasan Desktop"),
|
||||
("Change Path", "Ubah Direktori"),
|
||||
("Create Folder", "Buat Folder"),
|
||||
("Please enter the folder name", "Silakan masukkan nama folder"),
|
||||
("Please enter the folder name", "Silahkan masukkan nama folder"),
|
||||
("Fix it", "Perbaiki"),
|
||||
("Warning", "Peringatan"),
|
||||
("Login screen using Wayland is not supported", "Login screen dengan Wayland tidak didukung"),
|
||||
@@ -206,11 +206,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Username", "Nama pengguna"),
|
||||
("Invalid port", "Kesalahan port"),
|
||||
("Closed manually by the peer", "Ditutup secara manual oleh rekan"),
|
||||
("Enable remote configuration modification", "Aktifkan modifikasi konfigurasi remote"),
|
||||
("Enable remote configuration modification", "Aktifkan modifikasi konfigurasi remotE"),
|
||||
("Run without install", "Jalankan tanpa menginstal"),
|
||||
("Connect via relay", "Sambungkan via relay"),
|
||||
("Always connect via relay", "Selalu terhubung melalui relay"),
|
||||
("whitelist_tip", "Hanya IP yang diizinkan dapat mengakses"),
|
||||
("whitelist_tip", "Hanya IP yang diizikan dapat mengakses"),
|
||||
("Login", "Masuk"),
|
||||
("Verify", "Verifikasi"),
|
||||
("Remember me", "Ingatkan saya"),
|
||||
@@ -228,7 +228,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Username missed", "Nama pengguna tidak sesuai"),
|
||||
("Password missed", "Kata sandi tidak sesuai"),
|
||||
("Wrong credentials", "Nama pengguna atau kata sandi salah"),
|
||||
("The verification code is incorrect or has expired", "Kode verifikasi salah atau sudah kadaluwarsa"),
|
||||
("The verification code is incorrect or has expired", "Kode verifikasi salah atau sudah kadaluarsa"),
|
||||
("Edit Tag", "Ubah Tag"),
|
||||
("Forget Password", "Lupakan Kata Sandi"),
|
||||
("Favorites", "Favorit"),
|
||||
@@ -303,11 +303,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("android_open_battery_optimizations_tip", "Jika anda ingin menonaktifkan fitur ini, buka halam pengaturan, cari dan pilih [Baterai], Uncheck [Tidak dibatasi]"),
|
||||
("Start on boot", "Mulai saat dihidupkan"),
|
||||
("Start the screen sharing service on boot, requires special permissions", "Mulai layanan berbagi layar saat sistem dinyalakan, memerlukan izin khusus."),
|
||||
("Connection not allowed", "Koneksi tidak diizinkan"),
|
||||
("Connection not allowed", "Koneksi tidak dizinkan"),
|
||||
("Legacy mode", "Mode lawas"),
|
||||
("Map mode", "Mode peta"),
|
||||
("Translate mode", "Mode terjemahan"),
|
||||
("Use permanent password", "Gunakan kata sandi permanen"),
|
||||
("Use permanent password", "Gunakan kata sandi permanaen"),
|
||||
("Use both passwords", "Gunakan kedua kata sandi"),
|
||||
("Set permanent password", "Setel kata sandi permanen"),
|
||||
("Enable remote restart", "Aktifkan Restart Secara Remote"),
|
||||
@@ -385,7 +385,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("This PC", "PC ini"),
|
||||
("or", "atau"),
|
||||
("Elevate", "Elevasi"),
|
||||
("Zoom cursor", "Perbesar Kursor"),
|
||||
("Zoom cursor", "Perbersar Kursor"),
|
||||
("Accept sessions via password", "Izinkan sesi dengan kata sandi"),
|
||||
("Accept sessions via click", "Izinkan sesi dengan klik"),
|
||||
("Accept sessions via both", "Izinkan sesi dengan keduanya"),
|
||||
@@ -405,7 +405,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Closed manually by web console", "Ditutup secara manual dari konsol web."),
|
||||
("Local keyboard type", "Tipe papan ketik"),
|
||||
("Select local keyboard type", "Pilih tipe papan ketik"),
|
||||
("software_render_tip", "Jika anda menggunakan kartu grafis Nvidia pada sistem linux dan jendela windows ditutup secara instan setelah terhubung, silakan ubah ke driver open-source Nouveau, dibutuhkan untuk merestart aplikasi"),
|
||||
("software_render_tip", "Jika anda menggunakan kartu grafis Nvidia pada sistem linux dan jendela windows ditutup secara instan setelah terhung, silahkan ubah ke driver open-source Nouveau, dibutukan untuk merestart aplikasi"),
|
||||
("Always use software rendering", "Selalu gunakan software rendering"),
|
||||
("config_input", "Untuk menggunakan input keyboard remote, anda perlu memberikan izin \"Pemantauan Input\" pada RustDesk"),
|
||||
("config_microphone", "Untuk berbicara secara remote, anda perlu memberikan izin \"Rekam Audio\" pada RustDesk"),
|
||||
@@ -441,7 +441,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Voice call", "Panggilan suara"),
|
||||
("Text chat", "Obrolan Teks"),
|
||||
("Stop voice call", "Hentikan panggilan suara"),
|
||||
("relay_hint_tip", "Tidak memungkinkan untuk terhubung secara langsung; anda bisa mencoba terhubung via relay. Selain itu, jika ingin menggunakan relay pada percobaan pertama, silakan tambah akhiran \"/r\" pada ID atau pilih \"Selalu terhubung via relay\" di pilihan sesi terbaru."),
|
||||
("relay_hint_tip", "Tidak memungkinkan untuk terhubung secara langsung; anda bisa mencoba terhubung via relay. Selain itu, jika ingin menggunakan relay pada percobaan pertama, silahkan tambah akhiran \"/r\" pada ID atau pilih \"Selalu terhubung via relay\" di pilihan sesi terbaru."),
|
||||
("Reconnect", "Sambungkan ulang"),
|
||||
("Codec", "Kodek"),
|
||||
("Resolution", "Resolusi"),
|
||||
@@ -522,7 +522,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("auto_disconnect_option_tip", "Secara otomatis akan menutup sesi ketika tidak ada aktivitas"),
|
||||
("Connection failed due to inactivity", "Secara otomatis akan terputus ketik tidak ada aktivitas."),
|
||||
("Check for software update on startup", "Periksa pembaruan aplikasi saat sistem dinyalakan."),
|
||||
("upgrade_rustdesk_server_pro_to_{}_tip", "Silakan perbarui RustDesk Server Pro ke versi {} atau yang lebih baru!"),
|
||||
("upgrade_rustdesk_server_pro_to_{}_tip", "Silahkan perbarui RustDesk Server Pro ke versi {} atau yang lebih baru!"),
|
||||
("pull_group_failed_tip", "Gagal memperbarui grup"),
|
||||
("Filter by intersection", "Filter berdasarkan persilangan"),
|
||||
("Remove wallpaper during incoming sessions", "Hilangkan latar dinding ketika ada sesi yang masuk"),
|
||||
@@ -568,7 +568,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("My address book", "Daftar Kontak"),
|
||||
("Personal", "Personal"),
|
||||
("Owner", "Pemilik"),
|
||||
("Set shared password", "Atur kata sandi kolaboratif"),
|
||||
("Set shared password", "Atus kata sandi kolaboratif"),
|
||||
("Exist in", "Ada di"),
|
||||
("Read-only", "Hanya baca"),
|
||||
("Read/Write", "Baca/Tulis"),
|
||||
@@ -634,7 +634,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Untagged", "Tanpa tag"),
|
||||
("new-version-of-{}-tip", "Versi {} sudah tersedia."),
|
||||
("Accessible devices", "Perangkat yang tersedia"),
|
||||
("upgrade_remote_rustdesk_client_to_{}_tip", "Silakan perbarui aplikasi RustDesk ke versi {} atau yang lebih baru pada komputer yang akan terhubung!"),
|
||||
("upgrade_remote_rustdesk_client_to_{}_tip", "Silahkan perbarui aplikasi RustDesk ke versi {} atau yang lebih baru pada komputer yang akan terhubung!"),
|
||||
("d3d_render_tip", "Ketika rendering D3D diaktifkan, layar kontrol jarak jauh bisa tampak hitam di beberapa komputer"),
|
||||
("Use D3D rendering", "Gunakan rendering D3D"),
|
||||
("Printer", "Printer"),
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "'{}' non può essere usato come scorciatoia."),
|
||||
("On", "ON"),
|
||||
("Off", "OFF"),
|
||||
("api_server_connection_tip", "Il server personalizzato usa 'HTTP non crittografato'. Per abilitare HTTPS contatta l'amministratore."),
|
||||
("api_server_empty_tip", "Con 'Server API' vuoto, il server personalizzato predefinito è 'HTTP'. Per abilitare HTTPS contatta l'amministratore."),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+5
-7
@@ -785,10 +785,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Configure shortcuts...", "Sneltoetsen configureren..."),
|
||||
("Enable keyboard shortcuts in remote session", "Sneltoetsen inschakelen in een sessie op afstand"),
|
||||
("shortcut-page-description", "Beschrijving van sneltoetsenpagina"),
|
||||
("shortcut-passthrough-tip", "Als deze optie is ingeschakeld, wordt elke geconfigureerde toetsencombinatie doorgestuurd naar het externe apparaat. Dit is handig als een geconfigureerde toetsencombinatie in conflict komt met een functie die op het externe apparaat nodig is."),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", "Doorsturen naar extern apparaat"),
|
||||
("Reset to defaults", "Terugzetten naar standaardinstellingen"),
|
||||
("shortcut-reset-confirm-tip", "Alle huidige toetsencombinaties worden teruggezet naar de standaardinstellingen. Wil je doorgaan?"),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", "Monitor"),
|
||||
("Keyboard", "Toetsenbord"),
|
||||
("Toggle fullscreen", "Volledig scherm wisselen"),
|
||||
@@ -803,17 +803,15 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Edit", "Bewerken"),
|
||||
("Save", "Opslaan"),
|
||||
("Set shortcut", "Sneltoets toewijzen"),
|
||||
("shortcut-recording-instruction", "Druk op de toetsencombinatie die je wilt gebruiken."),
|
||||
("shortcut-recording-press-keys-tip", "Druk op de toetsencombinatie..."),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", "Sneltoets moet een combinatietoets bevatten"),
|
||||
("shortcut-already-bound-to", "Sneltoets is al toegewezen aan"),
|
||||
("Replace", "Vervangen"),
|
||||
("Valid", "Geldig"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Voor het opnemen is een fysiek toetsenbord vereist. Schermtoetsenborden worden niet ondersteund."),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", "Sneltoets wordt niet ondersteund"),
|
||||
("On", "Aan"),
|
||||
("Off", "Uit"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+32
-34
@@ -781,39 +781,37 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Relay fallback delay in seconds", "Opóźnienie przed przejściem na przekaźnik w sekundach"),
|
||||
("relay-fallback-delay-tip", "Jak długo nawiązane już połączenie przez przekaźnik czeka na bezpośrednie połączenie WebRTC, zanim zostanie użyte zamiast niego. Zwiększ, aby dać wolnemu połączeniu bezpośredniemu więcej czasu; zmniejsz, aby w sieciach, w których połączenie bezpośrednie jest niemożliwe, szybciej przechodzić na przekaźnik. Pozostaw puste, aby użyć wartości domyślnej 2.5 sekundy."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Aby rozpocząć połączenie głosowe, włącz opcję \"Przechwytywanie dźwięku\" na stronie \"Udostępnianie ekranu\"."),
|
||||
("Keyboard shortcuts", "Skróty klawiszowe"),
|
||||
("Configure shortcuts...", "Skonfiguruj skróty"),
|
||||
("Enable keyboard shortcuts in remote session", "Włącz skróty klawiszowe w zdalnych sesjach"),
|
||||
("shortcut-page-description", "Przypisz kombinację klawiszy do każdej poniższej akcji sesji. Każde powiązanie musi zawierać co najmniej jeden modyfikator."),
|
||||
("shortcut-passthrough-tip", "Po włączeniu wszystkie powiązane kombinacje są przekazywane do sesji zdalnej. Jest to przydatne, gdy powiązanie koliduje z czymś, czego potrzebujesz w sesji zdalnej."),
|
||||
("Pass-through to remote", "Przenieś do zdalnej sesji"),
|
||||
("Reset to defaults", "Przywróć domyślne"),
|
||||
("shortcut-reset-confirm-tip", "Wszystkie obecne przypisania zostaną zastąpione domyślnymi. Kontynuować?"),
|
||||
("Monitor", "Monitor"),
|
||||
("Keyboard", "Klawiatura"),
|
||||
("Toggle fullscreen", "Przełącz na pełny ekran"),
|
||||
("Switch to next display", "Przełącz na następny ekran"),
|
||||
("Switch to previous display", "Przełącz na poprzedni ekran"),
|
||||
("Switch to next tab", "Przełącz na następną zakładkę"),
|
||||
("Switch to previous tab", "Przełącz na poprzednią zakładkę"),
|
||||
("Toggle session recording", "Włącz/wyłącz nagrywanie sesji"),
|
||||
("Close tab", "Zamknij zakładkę"),
|
||||
("Toggle toolbar", "Włącz/wyłącz pasek narzędziowy"),
|
||||
("Toggle input source", "Włącz/wyłącz źródło wejściowe"),
|
||||
("Edit", "Edytuj"),
|
||||
("Save", "Zapisz"),
|
||||
("Set shortcut", "Ustaw skrót"),
|
||||
("shortcut-recording-instruction", "Naciśnij kombinację klawiszy, których chcesz użyć."),
|
||||
("shortcut-recording-press-keys-tip", "Naciśnij kombinację klawiszy..."),
|
||||
("shortcut-must-include-modifiers", "Musi zawierać co najmniej jeden modyfikator: {}"),
|
||||
("shortcut-already-bound-to", "Już przypisano do"),
|
||||
("Replace", "Zastąp"),
|
||||
("Valid", "Poprawny"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Do nagrywania potrzebna jest klawiatura fizyczna. Klawiatury programowe nie są obsługiwane."),
|
||||
("shortcut-key-not-supported", "Znak '{}' nie może być użyty jako skrót."),
|
||||
("On", "Włączone"),
|
||||
("Off", "Wyłączone"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
("Keyboard shortcuts", ""),
|
||||
("Configure shortcuts...", ""),
|
||||
("Enable keyboard shortcuts in remote session", ""),
|
||||
("shortcut-page-description", ""),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", ""),
|
||||
("Reset to defaults", ""),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", ""),
|
||||
("Keyboard", ""),
|
||||
("Toggle fullscreen", ""),
|
||||
("Switch to next display", ""),
|
||||
("Switch to previous display", ""),
|
||||
("Switch to next tab", ""),
|
||||
("Switch to previous tab", ""),
|
||||
("Toggle session recording", ""),
|
||||
("Close tab", ""),
|
||||
("Toggle toolbar", ""),
|
||||
("Toggle input source", ""),
|
||||
("Edit", ""),
|
||||
("Save", ""),
|
||||
("Set shortcut", ""),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", ""),
|
||||
("shortcut-already-bound-to", ""),
|
||||
("Replace", ""),
|
||||
("Valid", ""),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "Não é possível usar \"{}\" como atalho."),
|
||||
("On", "Ativado"),
|
||||
("Off", "Desativado"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+32
-34
@@ -781,39 +781,37 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
|
||||
("relay-fallback-delay-tip", "Quanto tempo uma ligação de retransmissão já estabelecida aguarda pela ligação direta WebRTC antes de ser usada em vez dela. Aumente para dar mais tempo a uma ligação direta lenta; diminua para recorrer mais cedo ao retransmissor em redes onde não é possível uma ligação direta. Deixe vazio para o valor predefinido de 2.5 segundos."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de Áudio\" na página \"Partilhar ecrã\"."),
|
||||
("Keyboard shortcuts", "Atalhos de teclado"),
|
||||
("Configure shortcuts...", "Configurar atalhos..."),
|
||||
("Enable keyboard shortcuts in remote session", "Ativar atalhos de teclado na sessão remota"),
|
||||
("shortcut-page-description", "Associe uma combinação de teclas a cada ação de sessão abaixo. Cada associação tem de incluir pelo menos uma tecla modificadora."),
|
||||
("shortcut-passthrough-tip", "Quando ativado, todas as combinações associadas são reencaminhadas para o remoto. Útil quando uma associação colide com algo de que precisa no remoto."),
|
||||
("Pass-through to remote", "Reencaminhar para o remoto"),
|
||||
("Reset to defaults", "Repor predefinições"),
|
||||
("shortcut-reset-confirm-tip", "Isto irá substituir todas as associações atuais pelo conjunto predefinido. Continuar?"),
|
||||
("Monitor", "Monitor"),
|
||||
("Keyboard", "Teclado"),
|
||||
("Toggle fullscreen", "Alternar ecrã inteiro"),
|
||||
("Switch to next display", "Mudar para o ecrã seguinte"),
|
||||
("Switch to previous display", "Mudar para o ecrã anterior"),
|
||||
("Switch to next tab", "Mudar para o separador seguinte"),
|
||||
("Switch to previous tab", "Mudar para o separador anterior"),
|
||||
("Toggle session recording", "Alternar gravação da sessão"),
|
||||
("Close tab", "Fechar separador"),
|
||||
("Toggle toolbar", "Alternar barra de ferramentas"),
|
||||
("Toggle input source", "Alternar fonte de entrada"),
|
||||
("Edit", "Editar"),
|
||||
("Save", "Guardar"),
|
||||
("Set shortcut", "Definir atalho"),
|
||||
("shortcut-recording-instruction", "Prima a combinação de teclas que pretende utilizar."),
|
||||
("shortcut-recording-press-keys-tip", "Prima uma combinação de teclas..."),
|
||||
("shortcut-must-include-modifiers", "Tem de incluir pelo menos uma tecla modificadora: {}"),
|
||||
("shortcut-already-bound-to", "Este atalho já está associado a"),
|
||||
("Replace", "Substituir"),
|
||||
("Valid", "Válido"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "A gravação requer um teclado físico. Os teclados virtuais não são suportados."),
|
||||
("shortcut-key-not-supported", "\"{}\" não pode ser usado como atalho."),
|
||||
("On", "Ligado"),
|
||||
("Off", "Desligado"),
|
||||
("api_server_connection_tip", "O seu servidor personalizado utiliza HTTP não encriptado. Contacte o seu administrador para ativar o HTTPS."),
|
||||
("api_server_empty_tip", "Com o servidor da API vazio, o seu servidor personalizado utiliza HTTP por predefinição. Contacte o seu administrador para ativar o HTTPS."),
|
||||
("Keyboard shortcuts", ""),
|
||||
("Configure shortcuts...", ""),
|
||||
("Enable keyboard shortcuts in remote session", ""),
|
||||
("shortcut-page-description", ""),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", ""),
|
||||
("Reset to defaults", ""),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", ""),
|
||||
("Keyboard", ""),
|
||||
("Toggle fullscreen", ""),
|
||||
("Switch to next display", ""),
|
||||
("Switch to previous display", ""),
|
||||
("Switch to next tab", ""),
|
||||
("Switch to previous tab", ""),
|
||||
("Toggle session recording", ""),
|
||||
("Close tab", ""),
|
||||
("Toggle toolbar", ""),
|
||||
("Toggle input source", ""),
|
||||
("Edit", ""),
|
||||
("Save", ""),
|
||||
("Set shortcut", ""),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", ""),
|
||||
("shortcut-already-bound-to", ""),
|
||||
("Replace", ""),
|
||||
("Valid", ""),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+32
-34
@@ -781,39 +781,37 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Relay fallback delay in seconds", "Задержка перед переходом на ретранслятор в секундах"),
|
||||
("relay-fallback-delay-tip", "Сколько времени уже установленное соединение через ретранслятор ждёт прямое соединение WebRTC, прежде чем будет использовано вместо него. Увеличьте, чтобы дать медленному прямому соединению больше времени; уменьшите, чтобы быстрее переходить на ретранслятор в сетях, где прямое соединение невозможно. Оставьте пустым для значения по умолчанию 2.5 секунды."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Чтобы начать голосовой вызов, включите \"Захват аудио\" на странице \"Демонстрация экрана\"."),
|
||||
("Keyboard shortcuts", "Сочетания клавиш"),
|
||||
("Configure shortcuts...", "Настроить сочетания клавиш..."),
|
||||
("Enable keyboard shortcuts in remote session", "Использовать сочетания клавиш в удалённом сеансе"),
|
||||
("shortcut-page-description", "Привязка сочетаний клавиш к действиям в сеансе. Каждое назначение должно включать хотя бы один модификатор."),
|
||||
("shortcut-passthrough-tip", "Если включено, каждое настроенное сочетаний клавиш пересылается на удалённое устройство. Полезно, если настроенное сочетание клавиш конфликтует с чем-то нужным на удалённом устройстве."),
|
||||
("Pass-through to remote", "Отправлять на удалённое устройство"),
|
||||
("Reset to defaults", "Сбросить настройки по умолчанию"),
|
||||
("shortcut-reset-confirm-tip", "Все текущие настроенные сочетания клавиш будут заменены на настройки по умолчанию. Продолжить?"),
|
||||
("Monitor", "Монитор"),
|
||||
("Keyboard", "Клавиатура"),
|
||||
("Toggle fullscreen", "Переключить полноэкранный режим"),
|
||||
("Switch to next display", "Переключиться на следующий дисплей"),
|
||||
("Switch to previous display", "Переключиться на предыдущий дисплей"),
|
||||
("Switch to next tab", "Переключиться на следующую вкладку"),
|
||||
("Switch to previous tab", "Переключиться на предыдущую вкладку"),
|
||||
("Toggle session recording", "Переключить запись сеанса"),
|
||||
("Close tab", "Закрыть вкладку"),
|
||||
("Toggle toolbar", "Переключить панель инструментов"),
|
||||
("Toggle input source", "Переключить источник ввода"),
|
||||
("Edit", "Изменить"),
|
||||
("Save", "Сохранить"),
|
||||
("Set shortcut", "Настроить сочетание клавиш"),
|
||||
("shortcut-recording-instruction", "Нажмите сочетание клавиш, которое хотите использовать."),
|
||||
("shortcut-recording-press-keys-tip", "Нажмите сочетание клавиш..."),
|
||||
("shortcut-must-include-modifiers", "Необходимо использовать хотя бы один модификатор: {}"),
|
||||
("shortcut-already-bound-to", "Уже привязано к"),
|
||||
("Replace", "Заменить"),
|
||||
("Valid", "Допустимо"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Для записи требуется физическая клавиатура. Экранные клавиатуры не поддерживаются."),
|
||||
("shortcut-key-not-supported", "\"{}\" невозможно использовать как сочетание клавиш."),
|
||||
("On", "вкл"),
|
||||
("Off", "откл"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
("Keyboard shortcuts", ""),
|
||||
("Configure shortcuts...", ""),
|
||||
("Enable keyboard shortcuts in remote session", ""),
|
||||
("shortcut-page-description", ""),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", ""),
|
||||
("Reset to defaults", ""),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", ""),
|
||||
("Keyboard", ""),
|
||||
("Toggle fullscreen", ""),
|
||||
("Switch to next display", ""),
|
||||
("Switch to previous display", ""),
|
||||
("Switch to next tab", ""),
|
||||
("Switch to previous tab", ""),
|
||||
("Toggle session recording", ""),
|
||||
("Close tab", ""),
|
||||
("Toggle toolbar", ""),
|
||||
("Toggle input source", ""),
|
||||
("Edit", ""),
|
||||
("Save", ""),
|
||||
("Set shortcut", ""),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", ""),
|
||||
("shortcut-already-bound-to", ""),
|
||||
("Replace", ""),
|
||||
("Valid", ""),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", "自訂伺服器正在使用未加密的 HTTP。請聯絡管理員啟用 HTTPS。"),
|
||||
("api_server_empty_tip", "API 伺服器留空時,自訂伺服器預設使用 HTTP。請聯絡管理員啟用 HTTPS。"),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,8 +813,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
|
||||
@@ -813,7 +813,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -18,10 +18,6 @@ fn main() {
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios", feature = "flutter")))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
#[cfg(windows)]
|
||||
if let Some(exit_code) = platform::handle_service_control() {
|
||||
return exit_code;
|
||||
}
|
||||
#[cfg(all(windows, not(feature = "inline")))]
|
||||
unsafe {
|
||||
winapi::um::shellscalingapi::SetProcessDpiAwareness(2);
|
||||
|
||||
+1
-61
@@ -891,43 +891,6 @@ fn get_all_term_values(uid: &str) -> Vec<String> {
|
||||
terms
|
||||
}
|
||||
|
||||
fn append_audio_latency_envs(
|
||||
envs: &mut Vec<(&'static str, String)>,
|
||||
get_var: impl Fn(&str) -> Option<String>,
|
||||
) {
|
||||
for key in ["PULSE_LATENCY_MSEC", "PIPEWIRE_LATENCY"] {
|
||||
if let Some(value) = get_var(key).filter(|value| !value.is_empty()) {
|
||||
envs.push((key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod audio_latency_env_tests {
|
||||
use super::append_audio_latency_envs;
|
||||
|
||||
#[test]
|
||||
fn forwards_configured_values_without_creating_defaults() {
|
||||
let mut envs = Vec::new();
|
||||
append_audio_latency_envs(&mut envs, |key| match key {
|
||||
"PULSE_LATENCY_MSEC" => Some("60".to_owned()),
|
||||
"PIPEWIRE_LATENCY" => Some("1024/48000".to_owned()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(
|
||||
envs,
|
||||
vec![
|
||||
("PULSE_LATENCY_MSEC", "60".to_owned()),
|
||||
("PIPEWIRE_LATENCY", "1024/48000".to_owned()),
|
||||
]
|
||||
);
|
||||
|
||||
envs.clear();
|
||||
append_audio_latency_envs(&mut envs, |_| None);
|
||||
assert!(envs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
|
||||
match desktop {
|
||||
@@ -958,9 +921,6 @@ fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
append_audio_latency_envs(&mut envs, |key| std::env::var(key).ok());
|
||||
|
||||
envs.push((
|
||||
"TERM",
|
||||
get_cur_term(&desktop.uid).unwrap_or_else(|| suggest_best_term()),
|
||||
@@ -1935,7 +1895,7 @@ fn get_width_height_from_captures<'t>(caps: &Captures<'t>) -> Option<(i32, i32)>
|
||||
#[inline]
|
||||
fn get_xrandr_conn_pat(name: &str) -> String {
|
||||
format!(
|
||||
r"(?m)^{}\s+connected.+?(?P<width>\d+)x(?P<height>\d+)\+(?P<x>\d+)\+(?P<y>\d+).*?\n",
|
||||
r"{}\s+connected.+?(?P<width>\d+)x(?P<height>\d+)\+(?P<x>\d+)\+(?P<y>\d+).*?\n",
|
||||
name
|
||||
)
|
||||
}
|
||||
@@ -2017,26 +1977,6 @@ pub fn current_resolution(name: &str) -> ResultType<Resolution> {
|
||||
bail!("Failed to find current resolution for {}", name);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod xrandr_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn output_name_does_not_match_inside_another_name() {
|
||||
let xrandr_output = "Screen 0: minimum 320 x 200, current 4480 x 1440, maximum 16384 x 16384
|
||||
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 309mm x 174mm
|
||||
1920x1080 60.01*+ 59.97
|
||||
1280x720 60.00
|
||||
DP-1 connected 2560x1440+1920+0 (normal left inverted right x axis y axis) 597mm x 336mm
|
||||
2560x1440 59.95*+
|
||||
1920x1080 60.00
|
||||
";
|
||||
let re = Regex::new(&get_xrandr_conn_pat("DP-1")).unwrap();
|
||||
let caps = re.captures(xrandr_output).unwrap();
|
||||
assert_eq!(get_width_height_from_captures(&caps), Some((2560, 1440)));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn change_resolution_directly(name: &str, width: usize, height: usize) -> ResultType<()> {
|
||||
Command::new("xrandr")
|
||||
.args(vec![
|
||||
|
||||
@@ -15,23 +15,6 @@
|
||||
#include <sddl.h>
|
||||
#include <memory>
|
||||
|
||||
#ifdef RUSTDESK_SCITER
|
||||
// Share the runner's service operations without loading either UI framework.
|
||||
#include "../../flutter/windows/runner/service_control.h"
|
||||
|
||||
extern "C" DWORD run_service_control()
|
||||
{
|
||||
int count = 0;
|
||||
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
|
||||
if (!args) {
|
||||
return GetLastError();
|
||||
}
|
||||
const DWORD result = service_control::RunCommand(count, args);
|
||||
LocalFree(args);
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
|
||||
extern "C" uint32_t get_session_user_info(PWSTR bufin, uint32_t nin, uint32_t id);
|
||||
|
||||
void flog(char const *fmt, ...)
|
||||
|
||||
+35
-138
@@ -97,7 +97,6 @@ use windows_service::{
|
||||
use winreg::{enums::*, RegKey};
|
||||
|
||||
mod acl;
|
||||
pub(crate) mod installer_files;
|
||||
mod installer_handoff;
|
||||
mod installer_shell;
|
||||
mod verified_update;
|
||||
@@ -108,10 +107,10 @@ pub use acl::{
|
||||
set_path_permission_for_portable_service_shmem_file,
|
||||
validate_path_for_portable_service_shmem_dir,
|
||||
};
|
||||
use installer_handoff::{run_cmds, InstallCommands};
|
||||
use installer_handoff::run_cmds;
|
||||
use installer_shell::{
|
||||
escape_nested_cmd_ampersands, shortcut_bytes, staged_shortcut_commands,
|
||||
staged_tray_shortcut_commands, validate_install_value,
|
||||
embedded_shortcut_commands, embedded_tray_shortcut_commands, escape_nested_cmd_ampersands,
|
||||
shortcut_bytes, validate_install_value,
|
||||
};
|
||||
pub use verified_update::{
|
||||
copy_and_verify_update_file_sha256, schedule_current_verified_update_file_cleanup,
|
||||
@@ -1676,16 +1675,18 @@ pub fn install_me(options: &str, path: String, silent: bool, debug: bool) -> Res
|
||||
// The elevated runner expands this to `%~f0.dir`, beside its protected copy.
|
||||
// Do not stage privileged shortcut artifacts in the user-writable `%TEMP%`.
|
||||
let tmp_path = "%RUSTDESK_OUTPUT_DIR%".to_owned();
|
||||
let (mk_shortcut_commands, mk_shortcut_file) = staged_shortcut_commands(
|
||||
let mk_shortcut_commands = embedded_shortcut_commands(
|
||||
shortcut_bytes(&exe, None, shortcut_icon_location.as_deref())?,
|
||||
&format!("{app_name}.lnk"),
|
||||
)?;
|
||||
let (uninstall_shortcut_commands, uninstall_shortcut_file) = staged_shortcut_commands(
|
||||
"mk_shortcut",
|
||||
);
|
||||
let uninstall_shortcut_commands = embedded_shortcut_commands(
|
||||
shortcut_bytes(&exe, Some("--uninstall"), Some("msiexec.exe"))?,
|
||||
&format!("Uninstall {app_name}.lnk"),
|
||||
)?;
|
||||
let (tray_shortcut_commands, tray_shortcut_file) =
|
||||
staged_tray_shortcut_commands(&app_name, &exe, shortcut_icon_location.as_deref())?;
|
||||
"uninstall_shortcut",
|
||||
);
|
||||
let tray_shortcut_commands =
|
||||
embedded_tray_shortcut_commands(&app_name, &exe, shortcut_icon_location.as_deref())?;
|
||||
let mut reg_value_desktop_shortcuts = "0".to_owned();
|
||||
let mut reg_value_start_menu_shortcuts = "0".to_owned();
|
||||
let mut reg_value_printer = "0".to_owned();
|
||||
@@ -1759,17 +1760,6 @@ copy /Y \"{tmp_path}\\{app_name} Tray.lnk\" \"%PROGRAMDATA%\\Microsoft\\Windows\
|
||||
"".to_owned()
|
||||
};
|
||||
|
||||
let after_install = get_after_install(
|
||||
&exe,
|
||||
Some(reg_value_start_menu_shortcuts),
|
||||
Some(reg_value_desktop_shortcuts),
|
||||
Some(reg_value_printer),
|
||||
);
|
||||
let after_install = native_after_install_commands(
|
||||
format!("{after_install}\r\n{install_remote_printer}"),
|
||||
&exe,
|
||||
true,
|
||||
)?;
|
||||
// Remember to check if `update_me` need to be changed if changing the `cmds`.
|
||||
// No need to merge the existing dup code, because the code in these two functions are too critical.
|
||||
// New code should be written in a common function.
|
||||
@@ -1801,25 +1791,25 @@ copy /Y \"{tmp_path}\\Uninstall {app_name}.lnk\" \"{path}\\\"
|
||||
{dels}
|
||||
{import_config}
|
||||
{after_install}
|
||||
{install_remote_printer}
|
||||
{sleep}
|
||||
",
|
||||
display_icon = shortcut_icon_location.as_deref().unwrap_or(exe.as_str()),
|
||||
nested_exe = escape_nested_cmd_ampersands(&exe),
|
||||
version = crate::VERSION.replace("-", "."),
|
||||
build_date = crate::BUILD_DATE,
|
||||
after_install = get_after_install(
|
||||
&exe,
|
||||
Some(reg_value_start_menu_shortcuts),
|
||||
Some(reg_value_desktop_shortcuts),
|
||||
Some(reg_value_printer)
|
||||
),
|
||||
sleep = if debug { "timeout 300" } else { "" },
|
||||
dels = if debug { "" } else { &dels },
|
||||
copy_exe = copy_exe_cmd(&src_exe, &exe, &path)?,
|
||||
import_config = get_import_config(&exe),
|
||||
);
|
||||
run_cmds(
|
||||
InstallCommands {
|
||||
script: cmds,
|
||||
files: vec![mk_shortcut_file, uninstall_shortcut_file, tray_shortcut_file],
|
||||
},
|
||||
debug,
|
||||
"install",
|
||||
)?;
|
||||
run_cmds(cmds, debug, "install")?;
|
||||
run_after_run_cmds(silent);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1827,30 +1817,29 @@ copy /Y \"{tmp_path}\\Uninstall {app_name}.lnk\" \"{path}\\\"
|
||||
pub fn run_after_install() -> ResultType<()> {
|
||||
let (_, _, _, exe) = get_install_info();
|
||||
run_cmds(
|
||||
native_after_install_commands(get_after_install(&exe, None, None, None), &exe, false)?,
|
||||
get_after_install(&exe, None, None, None),
|
||||
true,
|
||||
"after_install",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn run_before_uninstall() -> ResultType<()> {
|
||||
run_cmds(get_before_uninstall(true)?, true, "before_install")
|
||||
run_cmds(get_before_uninstall(true), true, "before_install")
|
||||
}
|
||||
|
||||
fn get_before_uninstall(kill_self: bool) -> ResultType<String> {
|
||||
fn get_before_uninstall(kill_self: bool) -> String {
|
||||
let app_name = crate::get_app_name();
|
||||
let (_, _, _, exe) = get_install_info();
|
||||
let remove_service = service_control_command("remove", &exe, false)?;
|
||||
let ext = app_name.to_lowercase();
|
||||
let filter = if kill_self {
|
||||
"".to_string()
|
||||
} else {
|
||||
format!(" /FI \"PID ne {}\"", get_current_pid())
|
||||
};
|
||||
Ok(format!(
|
||||
format!(
|
||||
"
|
||||
chcp 65001
|
||||
{remove_service}
|
||||
sc stop {app_name}
|
||||
sc delete {app_name}
|
||||
taskkill /F /IM {broker_exe}
|
||||
taskkill /F /IM {app_name}.exe{filter}
|
||||
reg delete HKEY_CLASSES_ROOT\\.{ext} /f
|
||||
@@ -1858,7 +1847,7 @@ fn get_before_uninstall(kill_self: bool) -> ResultType<String> {
|
||||
netsh advfirewall firewall delete rule name=\"{app_name} Service\"
|
||||
",
|
||||
broker_exe = WIN_TOPMOST_INJECTED_PROCESS_EXE,
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructs the uninstall command string for the application.
|
||||
@@ -1905,7 +1894,7 @@ fn get_uninstall(kill_self: bool, uninstall_printer: bool) -> ResultType<String>
|
||||
if exist \"%PUBLIC%\\Desktop\\{app_name}.lnk\" del /f /q \"%PUBLIC%\\Desktop\\{app_name}.lnk\"
|
||||
if exist \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\" del /f /q \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\"
|
||||
",
|
||||
before_uninstall=get_before_uninstall(kill_self)?,
|
||||
before_uninstall=get_before_uninstall(kill_self),
|
||||
uninstall_amyuni_idd=get_uninstall_amyuni_idd(),
|
||||
app_name = crate::get_app_name(),
|
||||
))
|
||||
@@ -3334,24 +3323,15 @@ pub fn try_lock_tray_single_instance() -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` on failure or cancellation so the caller keeps running.
|
||||
/// Successful removal exits this process instead of returning.
|
||||
pub fn uninstall_service(show_new_window: bool, _: bool) -> bool {
|
||||
log::info!("Uninstalling service...");
|
||||
let filter = format!(" /FI \"PID ne {}\"", get_current_pid());
|
||||
let (_, _, _, exe) = get_install_info();
|
||||
let remove_service = match service_control_command("remove", &exe, false) {
|
||||
Ok(commands) => commands,
|
||||
Err(err) => {
|
||||
log::error!("Failed to prepare service removal: {err}");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
Config::set_option("stop-service".into(), "Y".into());
|
||||
let cmds = format!(
|
||||
"
|
||||
chcp 65001
|
||||
{remove_service}
|
||||
sc stop {app_name}
|
||||
sc delete {app_name}
|
||||
if exist \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\" del /f /q \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\"
|
||||
taskkill /F /IM {broker_exe}
|
||||
taskkill /F /IM {app_name}.exe{filter}
|
||||
@@ -3368,7 +3348,7 @@ pub fn uninstall_service(show_new_window: bool, _: bool) -> bool {
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
fn get_install_service_commands(path: &str, exe: &str) -> ResultType<InstallCommands> {
|
||||
fn get_install_service_commands(path: &str, exe: &str) -> ResultType<String> {
|
||||
let app_name = crate::get_app_name();
|
||||
for value in [path, exe] {
|
||||
validate_install_value(value)?;
|
||||
@@ -3383,10 +3363,10 @@ fn get_install_service_commands(path: &str, exe: &str) -> ResultType<InstallComm
|
||||
if let Some(icon) = shortcut_icon_location.as_deref() {
|
||||
validate_install_value(icon)?;
|
||||
}
|
||||
let (tray_shortcut_commands, tray_shortcut_file) =
|
||||
staged_tray_shortcut_commands(&app_name, exe, shortcut_icon_location.as_deref())?;
|
||||
let tray_shortcut_commands =
|
||||
embedded_tray_shortcut_commands(&app_name, exe, shortcut_icon_location.as_deref())?;
|
||||
let filter = format!(" /FI \"PID ne {}\"", get_current_pid());
|
||||
let script = format!(
|
||||
Ok(format!(
|
||||
"
|
||||
chcp 65001
|
||||
taskkill /F /IM {app_name}.exe{filter}
|
||||
@@ -3396,12 +3376,8 @@ copy /Y \"%RUSTDESK_OUTPUT_DIR%\\{app_name} Tray.lnk\" \"%PROGRAMDATA%\\Microsof
|
||||
{create_service}
|
||||
",
|
||||
import_config = get_import_config(exe),
|
||||
create_service = service_control_command("create-service-with-rollback", exe, false)?,
|
||||
);
|
||||
Ok(InstallCommands {
|
||||
script,
|
||||
files: vec![tray_shortcut_file],
|
||||
})
|
||||
create_service = get_create_service(exe),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn install_service() -> bool {
|
||||
@@ -3952,86 +3928,7 @@ pub fn update_me_msi(msi: &str, expected_sha256: &str, quiet: bool) -> ResultTyp
|
||||
verified_update::install_verified_msi(msi, expected_sha256, quiet)
|
||||
}
|
||||
|
||||
fn native_after_install_commands(
|
||||
commands: String,
|
||||
exe: &str,
|
||||
installed_now: bool,
|
||||
) -> ResultType<String> {
|
||||
let service = get_create_service(exe);
|
||||
if service.is_empty() {
|
||||
return Ok(commands);
|
||||
}
|
||||
let native_service = service_control_command("create-service", exe, installed_now)?;
|
||||
if native_service == service {
|
||||
return Ok(commands);
|
||||
}
|
||||
// Complete independent setup before service-start errors can exit the BAT.
|
||||
Ok(format!(
|
||||
"{}\r\n{native_service}",
|
||||
commands.replacen(&service, "", 1)
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "flutter"))]
|
||||
pub fn handle_service_control() -> Option<std::process::ExitCode> {
|
||||
if std::env::args_os().nth(1).as_deref() != Some(std::ffi::OsStr::new("--service-control")) {
|
||||
return None;
|
||||
}
|
||||
extern "C" {
|
||||
fn run_service_control() -> u32;
|
||||
}
|
||||
let error = unsafe { run_service_control() };
|
||||
Some(if error == ERROR_SUCCESS {
|
||||
std::process::ExitCode::SUCCESS
|
||||
} else {
|
||||
eprintln!(
|
||||
"RustDesk service control failed: {}",
|
||||
std::io::Error::from_raw_os_error(error as i32)
|
||||
);
|
||||
std::process::ExitCode::FAILURE
|
||||
})
|
||||
}
|
||||
|
||||
fn service_control_command(operation: &str, exe: &str, installed_now: bool) -> ResultType<String> {
|
||||
let app_name = crate::get_app_name();
|
||||
let is_create = matches!(operation, "create-service" | "create-service-with-rollback");
|
||||
let legacy = match operation {
|
||||
"create-service" | "create-service-with-rollback" => get_create_service(exe),
|
||||
"remove" => format!("sc stop {app_name}\r\nsc delete {app_name}"),
|
||||
_ => bail!("Unsupported service operation: {operation}"),
|
||||
};
|
||||
if legacy.is_empty() || (is_create && Config::get_option("stop-service") == "Y") {
|
||||
return Ok(legacy);
|
||||
}
|
||||
// A fresh installation has just copied this runner. Otherwise only use the
|
||||
// new command when the caller is the installed executable; other versions
|
||||
// may not recognize it.
|
||||
if !installed_now {
|
||||
let current = std::env::current_exe()?;
|
||||
let current = current
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Current executable path is not valid Unicode"))?;
|
||||
if !current.eq_ignore_ascii_case(exe) {
|
||||
log::debug!("Keeping legacy service commands for a different installed executable");
|
||||
return Ok(legacy);
|
||||
}
|
||||
}
|
||||
validate_install_value(exe)?;
|
||||
let executable_argument = if is_create {
|
||||
format!(" \"{exe}\"")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Ok(format!(
|
||||
"start \"\" /b /wait \"{exe}\" --service-control {operation} \"{app_name}\"{executable_argument}\r\n\
|
||||
if not \"%errorlevel%\"==\"0\" exit /b %errorlevel%"
|
||||
))
|
||||
}
|
||||
|
||||
fn get_import_config(exe: &str) -> String {
|
||||
// --import-config does not register a service dispatcher, so SCM can report
|
||||
// a start failure even when import runs. Preserve this legacy contract for
|
||||
// older installed executables.
|
||||
if config::is_outgoing_only() {
|
||||
return "".to_string();
|
||||
}
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
use super::{installer_handoff::directory, wide_string};
|
||||
use hbb_common::{anyhow::anyhow, log, ResultType};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{self, Read},
|
||||
os::windows::io::{AsRawHandle, FromRawHandle},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use windows::{
|
||||
core::{w, Owned, PCWSTR},
|
||||
Win32::{
|
||||
Foundation::{DuplicateHandle, GENERIC_READ, GENERIC_WRITE, HANDLE, HLOCAL},
|
||||
Security::{
|
||||
Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
|
||||
},
|
||||
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
|
||||
},
|
||||
Storage::FileSystem::{
|
||||
CreateFileW, FileDispositionInfo, SetFileInformationByHandle, CREATE_NEW, DELETE,
|
||||
FILE_ATTRIBUTE_NORMAL, FILE_DISPOSITION_INFO, FILE_SHARE_READ,
|
||||
},
|
||||
System::Threading::GetCurrentProcess,
|
||||
},
|
||||
};
|
||||
|
||||
// Stage data before elevation instead of relaunching a verifier from a portable
|
||||
// directory whose executable or DLLs could be replaced while UAC is pending.
|
||||
pub(super) struct ProtectedInstallFile {
|
||||
path: PathBuf,
|
||||
cleanup_handle: Option<Owned<HANDLE>>,
|
||||
}
|
||||
|
||||
impl ProtectedInstallFile {
|
||||
pub(super) fn new(path: &Path, bytes: &[u8]) -> ResultType<Self> {
|
||||
Self::create(path, &mut io::Cursor::new(bytes), None)
|
||||
}
|
||||
|
||||
pub(super) fn copy_verified(source: &Path, expected_sha256: &str) -> ResultType<Self> {
|
||||
let mut source = File::open(source)?;
|
||||
let path = directory::path()?.with_extension("tmp");
|
||||
Self::create(&path, &mut source, Some(expected_sha256))
|
||||
}
|
||||
|
||||
fn create(
|
||||
path: &Path,
|
||||
source: &mut impl Read,
|
||||
expected_sha256: Option<&str>,
|
||||
) -> ResultType<Self> {
|
||||
let mut file = create_protected_file(path)?;
|
||||
let result = (|| -> ResultType<Owned<HANDLE>> {
|
||||
io::copy(source, &mut file)?;
|
||||
file.sync_all()?;
|
||||
if let Some(expected) = expected_sha256 {
|
||||
crate::update_hash::verify_sha256_reader(&mut file, expected).map_err(|error| {
|
||||
anyhow!(
|
||||
"Failed to verify staged installer file {}: {error:?}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
duplicate_cleanup_handle(&file)
|
||||
})();
|
||||
let cleanup_handle = result.map_err(|error| {
|
||||
// The initial handle can remove an incomplete file without reopening its protected path.
|
||||
if let Err(cleanup_error) = delete_staged_file(HANDLE(file.as_raw_handle())) {
|
||||
log::warn!(
|
||||
"Failed to remove incomplete installer file {}: {cleanup_error}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
error
|
||||
})?;
|
||||
Ok(Self {
|
||||
path: path.to_owned(),
|
||||
cleanup_handle: Some(cleanup_handle),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
pub(super) fn release(&mut self) {
|
||||
// cmd.exe cannot read/copy these files while a DELETE handle is open.
|
||||
// The handoff gate keeps it waiting until every staged handle is closed.
|
||||
drop(self.cleanup_handle.take());
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProtectedInstallFile {
|
||||
fn drop(&mut self) {
|
||||
// Cancellation cannot reopen the protected path with DELETE permission.
|
||||
let result = match &self.cleanup_handle {
|
||||
Some(handle) => delete_staged_file(**handle),
|
||||
None => match fs::remove_file(&self.path) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error.into()),
|
||||
_ => Ok(()),
|
||||
},
|
||||
};
|
||||
if let Err(error) = result {
|
||||
log::warn!(
|
||||
"Protected installer file may remain at {}: {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_protected_file(path: &Path) -> ResultType<File> {
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
// Restrict OWNER RIGHTS at creation so the unelevated creator cannot reopen
|
||||
// the file for writing or grant itself that permission after staging.
|
||||
unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
w!("D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;OW)"),
|
||||
SDDL_REVISION_1,
|
||||
&mut descriptor,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: false.into(),
|
||||
};
|
||||
let path_string = path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Invalid protected installer path"))?;
|
||||
let path_string = wide_string(path_string);
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
PCWSTR(path_string.as_ptr()),
|
||||
GENERIC_READ.0 | GENERIC_WRITE.0 | DELETE.0,
|
||||
FILE_SHARE_READ,
|
||||
Some(&attributes),
|
||||
CREATE_NEW,
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|error| {
|
||||
anyhow!(
|
||||
"Failed to create protected installer file {}: {error}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
Ok(unsafe { File::from_raw_handle(handle.0) })
|
||||
}
|
||||
|
||||
fn duplicate_cleanup_handle(file: &File) -> ResultType<Owned<HANDLE>> {
|
||||
let mut handle = HANDLE::default();
|
||||
// Retain deletion capability, not a writable handle, while waiting for UAC.
|
||||
unsafe {
|
||||
let process = GetCurrentProcess();
|
||||
DuplicateHandle(
|
||||
process,
|
||||
HANDLE(file.as_raw_handle()),
|
||||
process,
|
||||
&mut handle,
|
||||
DELETE.0,
|
||||
false,
|
||||
Default::default(),
|
||||
)?;
|
||||
Ok(Owned::new(handle))
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_staged_file(handle: HANDLE) -> ResultType<()> {
|
||||
let disposition = FILE_DISPOSITION_INFO {
|
||||
DeleteFile: true.into(),
|
||||
};
|
||||
unsafe {
|
||||
SetFileInformationByHandle(
|
||||
handle,
|
||||
FileDispositionInfo,
|
||||
&disposition as *const _ as *const _,
|
||||
std::mem::size_of_val(&disposition) as u32,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows::{
|
||||
core::BOOL,
|
||||
Win32::{
|
||||
Foundation::HANDLE,
|
||||
Security::{
|
||||
AccessCheck,
|
||||
Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
CreateRestrictedToken, CreateWellKnownSid, DuplicateToken, SecurityImpersonation,
|
||||
WinBuiltinAdministratorsSid, DACL_SECURITY_INFORMATION, DISABLE_MAX_PRIVILEGE,
|
||||
GENERIC_MAPPING, GROUP_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
PRIVILEGE_SET, PSID, SECURITY_MAX_SID_SIZE, SID_AND_ATTRIBUTES, TOKEN_DUPLICATE,
|
||||
TOKEN_QUERY,
|
||||
},
|
||||
Storage::FileSystem::{
|
||||
FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
|
||||
},
|
||||
System::Threading::{GetCurrentProcess, OpenProcessToken},
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn cancelled_staging_removes_files_without_parent_delete_permission() {
|
||||
use windows::Win32::Security::{ImpersonateLoggedOnUser, RevertToSelf};
|
||||
let root = std::env::temp_dir().join(format!("rustdesk-cancel-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let path = root.join("package.tmp");
|
||||
let file = ProtectedInstallFile::new(&path, b"cancelled update").unwrap();
|
||||
// Omit DELETE_CHILD as in Windows Temp, but retain fixture ACL control.
|
||||
set_parent_acl(&root, w!("D:P(A;;0x1600af;;;OW)"));
|
||||
unsafe {
|
||||
let token = ordinary_owner_token();
|
||||
ImpersonateLoggedOnUser(*token).unwrap();
|
||||
drop(file);
|
||||
RevertToSelf().unwrap();
|
||||
}
|
||||
set_parent_acl(&root, w!("D:P(A;;FA;;;OW)"));
|
||||
let remaining = fs::symlink_metadata(&path);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert!(
|
||||
matches!(remaining, Err(error) if error.kind() == io::ErrorKind::NotFound),
|
||||
"Cancelled staging must remove the protected package"
|
||||
);
|
||||
}
|
||||
|
||||
fn set_parent_acl(path: &Path, sddl: PCWSTR) {
|
||||
use windows::Win32::Security::{SetFileSecurityW, PROTECTED_DACL_SECURITY_INFORMATION};
|
||||
let path = wide_string(path.to_str().unwrap());
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
sddl,
|
||||
SDDL_REVISION_1,
|
||||
&mut descriptor,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let _descriptor = Owned::new(HLOCAL(descriptor.0));
|
||||
assert!(SetFileSecurityW(
|
||||
PCWSTR(path.as_ptr()),
|
||||
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
descriptor
|
||||
)
|
||||
.as_bool());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_files_protect_contents_and_remove_unverified_data() {
|
||||
const HASH: &str = "304ca1638c5effa6832e0e15b958a8f74847efe4df9c3f3187216e921c168fed";
|
||||
let root = std::env::temp_dir().join(format!("rustdesk-staging-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let path = root.join("input.tmp");
|
||||
let file =
|
||||
ProtectedInstallFile::create(&path, &mut io::Cursor::new(b"rustdesk"), Some(HASH))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ordinary_owner_access(file.path()),
|
||||
(FILE_GENERIC_READ | FILE_GENERIC_EXECUTE).0
|
||||
);
|
||||
assert_eq!(fs::read(file.path()).unwrap(), b"rustdesk");
|
||||
assert!(ProtectedInstallFile::new(&path, b"replacement").is_err());
|
||||
let rejected = root.join("rejected.tmp");
|
||||
assert!(ProtectedInstallFile::create(
|
||||
&rejected,
|
||||
&mut io::Cursor::new(b"changed"),
|
||||
Some(HASH)
|
||||
)
|
||||
.is_err());
|
||||
assert!(!rejected.exists());
|
||||
drop(file);
|
||||
fs::remove_dir(root).unwrap();
|
||||
}
|
||||
|
||||
fn ordinary_owner_access(path: &Path) -> u32 {
|
||||
let path = wide_string(path.to_str().unwrap());
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
PCWSTR(path.as_ptr()),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut descriptor,
|
||||
)
|
||||
.ok()
|
||||
.unwrap();
|
||||
}
|
||||
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
|
||||
let token = ordinary_owner_token();
|
||||
let mapping = GENERIC_MAPPING {
|
||||
GenericRead: FILE_GENERIC_READ.0,
|
||||
GenericWrite: FILE_GENERIC_WRITE.0,
|
||||
GenericExecute: FILE_GENERIC_EXECUTE.0,
|
||||
GenericAll: FILE_ALL_ACCESS.0,
|
||||
};
|
||||
let mut privileges = PRIVILEGE_SET::default();
|
||||
let mut size = std::mem::size_of::<PRIVILEGE_SET>() as u32;
|
||||
let mut granted = 0;
|
||||
let mut allowed = BOOL::default();
|
||||
unsafe {
|
||||
AccessCheck(
|
||||
descriptor,
|
||||
*token,
|
||||
winapi::um::winnt::MAXIMUM_ALLOWED,
|
||||
&mapping,
|
||||
Some(&mut privileges),
|
||||
&mut size,
|
||||
&mut granted,
|
||||
&mut allowed,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(allowed.as_bool());
|
||||
granted
|
||||
}
|
||||
|
||||
fn ordinary_owner_token() -> Owned<HANDLE> {
|
||||
let mut original = HANDLE::default();
|
||||
unsafe {
|
||||
OpenProcessToken(
|
||||
GetCurrentProcess(),
|
||||
TOKEN_QUERY | TOKEN_DUPLICATE,
|
||||
&mut original,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let original = unsafe { Owned::new(original) };
|
||||
let mut sid = [0; SECURITY_MAX_SID_SIZE as usize];
|
||||
let sid_pointer = PSID(sid.as_mut_ptr().cast());
|
||||
let mut size = sid.len() as u32;
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
None,
|
||||
Some(sid_pointer),
|
||||
&mut size,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let disabled = [SID_AND_ATTRIBUTES {
|
||||
Sid: sid_pointer,
|
||||
Attributes: 0,
|
||||
}];
|
||||
let mut restricted = HANDLE::default();
|
||||
unsafe {
|
||||
CreateRestrictedToken(
|
||||
*original,
|
||||
DISABLE_MAX_PRIVILEGE,
|
||||
Some(&disabled),
|
||||
None,
|
||||
None,
|
||||
&mut restricted,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let restricted = unsafe { Owned::new(restricted) };
|
||||
let mut impersonation = HANDLE::default();
|
||||
unsafe {
|
||||
DuplicateToken(*restricted, SecurityImpersonation, &mut impersonation).unwrap();
|
||||
}
|
||||
unsafe { Owned::new(impersonation) }
|
||||
}
|
||||
}
|
||||
@@ -1,136 +1,152 @@
|
||||
pub(super) mod directory;
|
||||
mod gate;
|
||||
|
||||
use super::{
|
||||
installer_files::ProtectedInstallFile,
|
||||
installer_shell::{
|
||||
get_system_executable, launch_elevated, path_for_cmd_environment,
|
||||
trusted_install_environment, BATCH_SHORTCUT_COPY_FAILURE_EXIT_CODE, CMD_RELATIVE_PATH,
|
||||
WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS,
|
||||
get_system_executable, path_for_cmd_assignment, path_for_cmd_environment,
|
||||
run_elevated_and_wait, trusted_install_environment,
|
||||
BATCH_SHORTCUT_DECODE_FAILURE_EXIT_CODE, CMD_RELATIVE_PATH,
|
||||
},
|
||||
validate_install_app_name, ResultType,
|
||||
};
|
||||
use gate::InstallGate;
|
||||
use hbb_common::{bail, log};
|
||||
use std::{fs, io, path::Path};
|
||||
use hbb_common::{
|
||||
bail, log,
|
||||
sha2::{Digest, Sha256},
|
||||
};
|
||||
use std::{
|
||||
fs,
|
||||
io::{self, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
const CERTUTIL_RELATIVE_PATH: &str = "certutil.exe";
|
||||
const CHCP_RELATIVE_PATH: &str = "chcp.com";
|
||||
const FINDSTR_RELATIVE_PATH: &str = "findstr.exe";
|
||||
const UTF8_CODE_PAGE: u32 = 65001;
|
||||
const INSTALL_HANDOFF_RUNNER_EXISTS_EXIT_CODE: u32 = 0x5253_0001;
|
||||
const INSTALL_HANDOFF_COPY_FAILURE_EXIT_CODE: u32 = 0x5253_0002;
|
||||
const INSTALL_HANDOFF_HASH_FAILURE_EXIT_CODE: u32 = 0x5253_0003;
|
||||
const INSTALL_HANDOFF_HASH_MISMATCH_EXIT_CODE: u32 = 0x5253_0004;
|
||||
const BATCH_CODE_PAGE_FAILURE_EXIT_CODE: u32 = 0x5253_0005;
|
||||
const BATCH_OUTPUT_DIRECTORY_EXISTS_EXIT_CODE: u32 = 0x5253_0006;
|
||||
const BATCH_OUTPUT_DIRECTORY_CREATE_FAILURE_EXIT_CODE: u32 = 0x5253_0007;
|
||||
const SHA256_HASH_LENGTH: usize = 32;
|
||||
|
||||
pub(super) struct InstallCommands {
|
||||
pub script: String,
|
||||
pub files: Vec<ProtectedInstallFile>,
|
||||
}
|
||||
|
||||
impl From<String> for InstallCommands {
|
||||
fn from(script: String) -> Self {
|
||||
Self {
|
||||
script,
|
||||
files: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
type BatchHash = [u8; SHA256_HASH_LENGTH];
|
||||
|
||||
struct InstallCommandScript {
|
||||
file: ProtectedInstallFile,
|
||||
_files: Vec<ProtectedInstallFile>,
|
||||
path: PathBuf,
|
||||
expected_hash: BatchHash,
|
||||
}
|
||||
|
||||
impl InstallCommandScript {
|
||||
fn release_files(&mut self) {
|
||||
self.file.release();
|
||||
for file in &mut self._files {
|
||||
file.release();
|
||||
impl Drop for InstallCommandScript {
|
||||
fn drop(&mut self) {
|
||||
if let Err(err) = fs::remove_file(&self.path) {
|
||||
if err.kind() != io::ErrorKind::NotFound {
|
||||
log::warn!(
|
||||
"Failed to remove temporary installer file {:?}: {err}",
|
||||
self.path
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_install_commands(cmds: &InstallCommands) -> ResultType<String> {
|
||||
let commands = cmds.script.replace("\r\n", "\n").replace('\n', "\r\n");
|
||||
fn prepare_install_commands(commands: &str) -> ResultType<String> {
|
||||
let commands = commands.replace("\r\n", "\n").replace('\n', "\r\n");
|
||||
let chcp_path = get_system_executable(CHCP_RELATIVE_PATH)?;
|
||||
let chcp = path_for_cmd_environment(&chcp_path)?;
|
||||
let files = cmds
|
||||
.files
|
||||
.iter()
|
||||
.map(|file| path_for_cmd_environment(file.path()).map(|path| format!("\"{path}\"")))
|
||||
.collect::<ResultType<Vec<_>>>()?
|
||||
.join(" ");
|
||||
// Call a fixed label so early EXIT /B still reaches cleanup, without reparsing a path.
|
||||
// Exit the dedicated cmd after self-deletion; EXIT /B would reopen the missing BAT.
|
||||
Ok(format!(
|
||||
"@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\n\
|
||||
set \"ERRORLEVEL=\"\r\n\
|
||||
call :rustdesk_install\r\n\
|
||||
set \"RUSTDESK_INSTALL_EXIT_CODE=%ERRORLEVEL%\"\r\n\
|
||||
rd /s /q \"%~f0.dir\" > nul 2>&1\r\n\
|
||||
(del /q \"%~f0\" {files} > nul 2>&1 & exit %RUSTDESK_INSTALL_EXIT_CODE%)\r\n\
|
||||
:rustdesk_install\r\n\
|
||||
\"{chcp}\" {UTF8_CODE_PAGE} > nul || exit /b \
|
||||
{BATCH_CODE_PAGE_FAILURE_EXIT_CODE}\r\n\
|
||||
{}\r\n\
|
||||
if exist \"%~f0.dir\" exit /b {BATCH_OUTPUT_DIRECTORY_EXISTS_EXIT_CODE}\r\n\
|
||||
md \"%~f0.dir\" || exit /b {BATCH_OUTPUT_DIRECTORY_CREATE_FAILURE_EXIT_CODE}\r\n\
|
||||
set \"RUSTDESK_OUTPUT_DIR=%~f0.dir\"\r\n{commands}\r\nexit /b 0\r\n",
|
||||
trusted_install_environment()?
|
||||
))
|
||||
}
|
||||
|
||||
fn write_install_script(cmds: InstallCommands, path: &Path) -> ResultType<InstallCommandScript> {
|
||||
fn write_install_script(cmds: String) -> ResultType<InstallCommandScript> {
|
||||
let directory = std::env::temp_dir();
|
||||
path_for_cmd_environment(&directory)?;
|
||||
let commands = prepare_install_commands(&cmds)?;
|
||||
Ok(InstallCommandScript {
|
||||
file: ProtectedInstallFile::new(path, commands.as_bytes())?,
|
||||
_files: cmds.files,
|
||||
})
|
||||
let expected_hash = Sha256::digest(commands.as_bytes()).into();
|
||||
let path = directory.join(format!(
|
||||
"rustdesk_install_{}.bat",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)?;
|
||||
let script = InstallCommandScript {
|
||||
path,
|
||||
expected_hash,
|
||||
};
|
||||
file.write_all(commands.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
Ok(script)
|
||||
}
|
||||
|
||||
fn protected_install_parameters(
|
||||
fn install_hash_pattern(hash: &BatchHash) -> String {
|
||||
hash.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" *")
|
||||
}
|
||||
|
||||
fn verified_install_bootstrap(
|
||||
script: &InstallCommandScript,
|
||||
gate: &InstallGate,
|
||||
runner_directory: &Path,
|
||||
) -> ResultType<String> {
|
||||
let path = path_for_cmd_environment(script.file.path())?;
|
||||
let pipe = gate.name();
|
||||
let parameters =
|
||||
format!("/D /E:ON /V:OFF /C \"set /p RUSTDESK_HANDOFF=<\"{pipe}\" >nul && \"{path}\"\"");
|
||||
let length = parameters.encode_utf16().count();
|
||||
if length >= WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS {
|
||||
bail!("Elevated command is too long: {length} UTF-16 characters");
|
||||
}
|
||||
Ok(parameters)
|
||||
let source = path_for_cmd_assignment(&script.path)?;
|
||||
let runner = runner_directory.join(format!(
|
||||
"rustdesk_install_{}.bat",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let runner = path_for_cmd_assignment(&runner)?;
|
||||
let cmd_path = get_system_executable(CMD_RELATIVE_PATH)?;
|
||||
let certutil_path = get_system_executable(CERTUTIL_RELATIVE_PATH)?;
|
||||
let findstr_path = get_system_executable(FINDSTR_RELATIVE_PATH)?;
|
||||
let cmd = path_for_cmd_assignment(&cmd_path)?;
|
||||
let certutil = path_for_cmd_assignment(&certutil_path)?;
|
||||
let findstr = path_for_cmd_assignment(&findstr_path)?;
|
||||
// Short names preserve headroom under the Windows 7 ShellExecuteExW 2,048
|
||||
// UTF-16-character parameter limit. Paths are stored with delayed expansion
|
||||
// disabled, then expanded indirectly so literal `!` survives: S=source,
|
||||
// R=runner, Q=cmd.exe, H=certutil.exe, F=findstr.exe, C=created flag, E=exit code.
|
||||
Ok(format!(
|
||||
"setlocal DisableDelayedExpansion & set \"S={source}\" & set \"R={runner}\" & \
|
||||
set \"Q={cmd}\" & set \"H={certutil}\" & set \"F={findstr}\" & \
|
||||
set \"C=0\" & set \"E=0\" & setlocal EnableDelayedExpansion & \
|
||||
if exist \"!R!\" (set \"E={INSTALL_HANDOFF_RUNNER_EXISTS_EXIT_CODE}\") else (\
|
||||
set \"C=1\" & copy /Y \"!S!\" \"!R!\" > nul || \
|
||||
(set \"E={INSTALL_HANDOFF_COPY_FAILURE_EXIT_CODE}\") & \
|
||||
if \"!E!\"==\"0\" (\"!H!\" -hashfile \"!R!\" SHA256 > \"!R!.hash\" || \
|
||||
set \"E={INSTALL_HANDOFF_HASH_FAILURE_EXIT_CODE}\") & \
|
||||
if \"!E!\"==\"0\" (\"!F!\" /R /I /X /C:\"{}\" \"!R!.hash\" > nul || \
|
||||
set \"E={INSTALL_HANDOFF_HASH_MISMATCH_EXIT_CODE}\") & \
|
||||
if \"!E!\"==\"0\" (\"!Q!\" /D /E:ON /V:OFF /C \"\"!R!\"\" & \
|
||||
set \"E=!errorlevel!\")) & \
|
||||
if \"!C!\"==\"1\" (rd /s /q \"!R!.dir\" > nul 2>&1 & \
|
||||
del /f /q \"!R!\" \"!R!.*\" > nul 2>&1) & exit /b !E!",
|
||||
install_hash_pattern(&script.expected_hash),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn run_cmds(cmds: impl Into<InstallCommands>, show: bool, tip: &str) -> ResultType<()> {
|
||||
fn verified_install_parameters(script: &InstallCommandScript) -> ResultType<String> {
|
||||
let system_directory = get_system_executable("")?;
|
||||
Ok(format!(
|
||||
"/D /E:ON /V:ON /C {}",
|
||||
verified_install_bootstrap(script, &system_directory)?
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn run_cmds(cmds: String, show: bool, tip: &str) -> ResultType<()> {
|
||||
validate_install_app_name(&crate::get_app_name())?;
|
||||
let path = directory::path()?.with_extension("bat");
|
||||
let directory = path.with_extension("bat.dir");
|
||||
let mut script = write_install_script(cmds.into(), &path)?;
|
||||
let script = write_install_script(cmds)?;
|
||||
let cmd_path = get_system_executable(CMD_RELATIVE_PATH)?;
|
||||
let gate = InstallGate::new()?;
|
||||
let parameters = protected_install_parameters(&script, &gate)?;
|
||||
directory::create(&directory)?;
|
||||
let process = launch_elevated(&cmd_path, ¶meters, show).map_err(|err| {
|
||||
log::debug!("Failed to launch elevated installer: {err:#}");
|
||||
err.context(format!(
|
||||
"Installer handoff failed; protected directory may remain at {}",
|
||||
directory.display()
|
||||
))
|
||||
})?;
|
||||
gate.wait_for_client(process.handle())?;
|
||||
// Keep DELETE-capable handles through UAC cancellation, but close them before
|
||||
// cmd opens the BAT or copies its inputs. The protected DACL stays unchanged.
|
||||
script.release_files();
|
||||
gate.release(process.handle())?;
|
||||
let exit_code = process.wait()?;
|
||||
// Cleanup must not change the result of an installation that already ran.
|
||||
match fs::symlink_metadata(&directory) {
|
||||
Ok(_) => log::warn!(
|
||||
"Protected installer directory may remain at {}",
|
||||
directory.display()
|
||||
),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => log::warn!(
|
||||
"Protected installer directory may remain at {}: {err}",
|
||||
directory.display()
|
||||
),
|
||||
}
|
||||
let parameters = verified_install_parameters(&script)?;
|
||||
let exit_code = run_elevated_and_wait(&cmd_path, ¶meters, show)?;
|
||||
if exit_code != 0 {
|
||||
bail!(
|
||||
"{tip} failed with elevated exit code {exit_code}: {}",
|
||||
@@ -142,111 +158,131 @@ pub(super) fn run_cmds(cmds: impl Into<InstallCommands>, show: bool, tip: &str)
|
||||
|
||||
fn elevated_install_failure_reason(exit_code: u32) -> &'static str {
|
||||
match exit_code {
|
||||
INSTALL_HANDOFF_RUNNER_EXISTS_EXIT_CODE => "protected runner already exists",
|
||||
INSTALL_HANDOFF_COPY_FAILURE_EXIT_CODE => "failed to copy protected runner",
|
||||
INSTALL_HANDOFF_HASH_FAILURE_EXIT_CODE => "failed to hash protected runner",
|
||||
INSTALL_HANDOFF_HASH_MISMATCH_EXIT_CODE => "protected runner hash mismatch",
|
||||
BATCH_CODE_PAGE_FAILURE_EXIT_CODE => "failed to set the installer code page",
|
||||
BATCH_SHORTCUT_COPY_FAILURE_EXIT_CODE => "failed to copy a prepared shortcut",
|
||||
BATCH_OUTPUT_DIRECTORY_EXISTS_EXIT_CODE => "installer output directory already exists",
|
||||
BATCH_OUTPUT_DIRECTORY_CREATE_FAILURE_EXIT_CODE => {
|
||||
"failed to create the installer output directory"
|
||||
}
|
||||
BATCH_SHORTCUT_DECODE_FAILURE_EXIT_CODE => "failed to decode an embedded shortcut",
|
||||
_ => "installer command failed",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::installer_shell::shortcut_bytes;
|
||||
use super::*;
|
||||
use std::{
|
||||
os::windows::{io::AsRawHandle, process::CommandExt},
|
||||
process::Stdio,
|
||||
use super::super::installer_shell::{
|
||||
embedded_shortcut_commands, shortcut_bytes, WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS,
|
||||
};
|
||||
use windows::Win32::Foundation::HANDLE;
|
||||
use super::*;
|
||||
use ::windows::Win32::System::Threading;
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
#[test]
|
||||
fn protected_handoff_preserves_shortcuts_failures_and_cleanup() {
|
||||
const COMMAND_FAILURE: u32 = 77;
|
||||
for exit_code in [0, COMMAND_FAILURE] {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("rustdesk-handoff-{}", uuid::Uuid::new_v4()));
|
||||
let source = root.join("source !&^@().bat");
|
||||
let runner = source.with_extension("bat.dir");
|
||||
fs::create_dir_all(&runner).unwrap();
|
||||
let bytes = shortcut_bytes(r"C:\RustDesk.exe", Some("--tray"), None).unwrap();
|
||||
let shortcut =
|
||||
ProtectedInstallFile::new(&root.join("shortcut !&^@().tmp"), &bytes).unwrap();
|
||||
let marker = root.join("copied.lnk");
|
||||
let commands = InstallCommands {
|
||||
script: format!(
|
||||
"copy /B /Y \"{}\" \"{}\" > nul\r\nexit /b {exit_code}",
|
||||
shortcut.path().display(),
|
||||
marker.display()
|
||||
),
|
||||
files: vec![shortcut],
|
||||
};
|
||||
let mut script = write_install_script(commands, &source).unwrap();
|
||||
if !super::super::is_elevated(None).unwrap() {
|
||||
assert!(fs::write(script.file.path(), "exit /b 0\r\n").is_err());
|
||||
}
|
||||
let output = run_script(&mut script, true);
|
||||
let copied = fs::read(&marker).unwrap();
|
||||
let cleaned = !runner.exists()
|
||||
&& !script.file.path().exists()
|
||||
&& script._files.iter().all(|file| !file.path().exists());
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(
|
||||
output.status.code().map(|code| code as u32),
|
||||
Some(exit_code),
|
||||
"{output:?}"
|
||||
);
|
||||
assert_eq!(copied, bytes);
|
||||
assert!(cleaned, "The runner and protected inputs must be removed");
|
||||
}
|
||||
fn native_install_handoff_verifies_before_execution() {
|
||||
let marker = std::env::temp_dir().join(format!(
|
||||
"rustdesk_install_marker_{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let runner_dir = std::env::temp_dir().join(format!(
|
||||
"rustdesk_install_!RUSTDESK_HANDOFF_EXPAND!&^@()runner_{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
std::fs::create_dir(&runner_dir).expect("runner directory should be created");
|
||||
let shortcut_commands = embedded_shortcut_commands(
|
||||
shortcut_bytes(r"C:\RustDesk.exe", None, None)
|
||||
.expect("native shortcut should be generated"),
|
||||
"test.lnk",
|
||||
"test",
|
||||
);
|
||||
let script = write_install_script(format!(
|
||||
"if \"%PROGRAMDATA%\"==\"rustdesk_untrusted\" exit /b 77\r\n\
|
||||
if \"%PUBLIC%\"==\"rustdesk_untrusted\" exit /b 77\r\n\
|
||||
{shortcut_commands}\r\n\
|
||||
> \"{}\" echo verified",
|
||||
marker.display()
|
||||
))
|
||||
.expect("install script should be created");
|
||||
let bootstrap = verified_install_bootstrap(&script, &runner_dir)
|
||||
.expect("native verifier bootstrap should be generated");
|
||||
assert_native_handoff_structure(&script, &shortcut_commands, &bootstrap);
|
||||
|
||||
let output = run_install_bootstrap_for_test(&bootstrap);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"unchanged script failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(marker.exists(), "verified install script must execute");
|
||||
std::fs::remove_file(&marker).expect("test marker should be removed");
|
||||
assert_replaced_install_script_is_rejected(&script, &runner_dir, &marker);
|
||||
std::fs::remove_dir(runner_dir).expect("runner directory should be empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_handoff_does_not_execute_the_batch() {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("rustdesk-interrupted-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let source = root.join("source.bat");
|
||||
let marker = root.join("executed");
|
||||
let commands = format!("echo unexpected > \"{}\"", marker.display());
|
||||
let mut script = write_install_script(commands.into(), &source).unwrap();
|
||||
let output = run_script(&mut script, false);
|
||||
assert!(!output.status.success(), "{output:?}");
|
||||
assert!(!marker.exists());
|
||||
drop(script);
|
||||
assert!(!source.exists());
|
||||
fs::remove_dir(&root).unwrap();
|
||||
|
||||
// A child exiting without connecting must also retire the pending pipe I/O.
|
||||
let gate = InstallGate::new().unwrap();
|
||||
let mut child =
|
||||
std::process::Command::new(get_system_executable(CMD_RELATIVE_PATH).unwrap())
|
||||
.args(["/D", "/C", "exit", "0"])
|
||||
.creation_flags(::windows::Win32::System::Threading::CREATE_NO_WINDOW.0)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
assert!(gate.wait_for_client(HANDLE(child.as_raw_handle())).is_err());
|
||||
assert!(child.wait().unwrap().success());
|
||||
fn assert_native_handoff_structure(
|
||||
script: &InstallCommandScript,
|
||||
shortcut_commands: &str,
|
||||
bootstrap: &str,
|
||||
) {
|
||||
assert!(shortcut_commands.contains("certutil"));
|
||||
assert!(shortcut_commands.contains("-decode"));
|
||||
assert!(!shortcut_commands.to_ascii_lowercase().contains("cscript"));
|
||||
assert!(!shortcut_commands
|
||||
.to_ascii_lowercase()
|
||||
.contains("powershell"));
|
||||
let win7_hash_pattern = script
|
||||
.expected_hash
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" *");
|
||||
assert!(bootstrap.contains(&format!("/R /I /X /C:\"{win7_hash_pattern}\"")));
|
||||
let parameters =
|
||||
verified_install_parameters(script).expect("elevated parameters should be generated");
|
||||
assert!(bootstrap.contains("certutil.exe"));
|
||||
assert!(bootstrap.contains("findstr.exe"));
|
||||
assert!(!bootstrap.to_ascii_lowercase().contains("powershell"));
|
||||
assert!(parameters.encode_utf16().count() < WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS);
|
||||
}
|
||||
|
||||
fn run_script(script: &mut InstallCommandScript, release: bool) -> std::process::Output {
|
||||
let gate = InstallGate::new().unwrap();
|
||||
let parameters = protected_install_parameters(script, &gate).unwrap();
|
||||
let mut child =
|
||||
std::process::Command::new(get_system_executable(CMD_RELATIVE_PATH).unwrap())
|
||||
.raw_arg(parameters)
|
||||
.creation_flags(::windows::Win32::System::Threading::CREATE_NO_WINDOW.0)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let process = HANDLE(child.as_raw_handle());
|
||||
gate.wait_for_client(process).unwrap();
|
||||
assert!(child.try_wait().unwrap().is_none());
|
||||
if release {
|
||||
script.release_files();
|
||||
gate.release(process).unwrap();
|
||||
} else {
|
||||
drop(gate);
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
fn assert_replaced_install_script_is_rejected(
|
||||
script: &InstallCommandScript,
|
||||
runner_dir: &Path,
|
||||
marker: &Path,
|
||||
) {
|
||||
std::fs::write(
|
||||
&script.path,
|
||||
format!("> \"{}\" echo hijacked\r\n", marker.display()),
|
||||
)
|
||||
.expect("install script should be replaceable");
|
||||
let replaced = verified_install_bootstrap(&script, &runner_dir)
|
||||
.expect("replacement verifier should be generated");
|
||||
let output = run_install_bootstrap_for_test(&replaced);
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"replaced script unexpectedly passed verification"
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(INSTALL_HANDOFF_HASH_MISMATCH_EXIT_CODE as i32)
|
||||
);
|
||||
assert!(!marker.exists(), "replaced script must not execute");
|
||||
}
|
||||
|
||||
fn run_install_bootstrap_for_test(bootstrap: &str) -> std::process::Output {
|
||||
let cmd = get_system_executable(CMD_RELATIVE_PATH).expect("system cmd.exe should resolve");
|
||||
let mut command = std::process::Command::new(cmd);
|
||||
command
|
||||
.env("PROGRAMDATA", "rustdesk_untrusted")
|
||||
.env("PUBLIC", "rustdesk_untrusted")
|
||||
.env("RUSTDESK_HANDOFF_EXPAND", "expanded");
|
||||
command.raw_arg(format!("/D /E:ON /V:ON /C {bootstrap}"));
|
||||
command
|
||||
.creation_flags(Threading::CREATE_NO_WINDOW.0)
|
||||
.output()
|
||||
.expect("native verifier should run")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
use super::super::{
|
||||
installer_shell::{get_system_executable, path_for_cmd_environment},
|
||||
wide_string,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use std::{
|
||||
fs, mem,
|
||||
os::windows::fs::MetadataExt,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use windows::{
|
||||
core::{w, PCWSTR},
|
||||
Win32::{
|
||||
Foundation::{LocalFree, HLOCAL},
|
||||
Security::{
|
||||
Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
|
||||
},
|
||||
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
|
||||
},
|
||||
Storage::FileSystem::{CreateDirectoryW, FILE_ATTRIBUTE_REPARSE_POINT},
|
||||
},
|
||||
};
|
||||
|
||||
pub(in crate::platform::windows) fn path() -> ResultType<PathBuf> {
|
||||
let system = get_system_executable("")?;
|
||||
let windows = system
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("System directory has no parent"))?;
|
||||
let temporary = windows.join("Temp");
|
||||
for parent in temporary.ancestors() {
|
||||
let metadata = fs::symlink_metadata(parent).map_err(|err| {
|
||||
anyhow!(
|
||||
"Failed to inspect installer temporary parent {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0 {
|
||||
bail!(
|
||||
"Installer temporary parent is not a regular directory: {}",
|
||||
parent.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(temporary.join(format!(
|
||||
"rustdesk-install-{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) fn create(path: &Path) -> ResultType<()> {
|
||||
let wide_path = wide_string(path_for_cmd_environment(path)?);
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
// OWNER RIGHTS removes the ordinary creator's implicit WRITE_DAC permission.
|
||||
// The owner can inspect the ACL, but only Administrators/SYSTEM can modify contents.
|
||||
// https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-special-identities-groups#owner-rights
|
||||
unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
w!("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)"),
|
||||
SDDL_REVISION_1,
|
||||
&mut descriptor,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: false.into(),
|
||||
};
|
||||
let result = unsafe { CreateDirectoryW(PCWSTR(wide_path.as_ptr()), Some(&attributes)) };
|
||||
unsafe { LocalFree(Some(HLOCAL(descriptor.0))) };
|
||||
result.map_err(|err| {
|
||||
anyhow!(
|
||||
"Failed to create protected installer directory {}: {err}",
|
||||
path.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use winapi::um::winnt::MAXIMUM_ALLOWED;
|
||||
use windows::{
|
||||
core::{Owned, BOOL},
|
||||
Win32::{
|
||||
Foundation::HANDLE,
|
||||
Security::{
|
||||
AccessCheck,
|
||||
Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DuplicateToken, SecurityImpersonation, DACL_SECURITY_INFORMATION, GENERIC_MAPPING,
|
||||
GROUP_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, PRIVILEGE_SET,
|
||||
TOKEN_DUPLICATE, TOKEN_QUERY,
|
||||
},
|
||||
Storage::FileSystem::{
|
||||
FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
|
||||
READ_CONTROL,
|
||||
},
|
||||
System::Threading::{GetCurrentProcess, OpenProcessToken},
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn protected_directory_enforces_creator_permissions() {
|
||||
let elevated =
|
||||
super::super::super::is_elevated(None).expect("creator elevation should be available");
|
||||
// The user-owned parent allows cleanup through DELETE_CHILD. AccessCheck
|
||||
// below checks the child's DACL, not that separate parent permission.
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"rustdesk_installer_acl_{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
create(&directory).expect("production directory creation should succeed");
|
||||
let access = creator_directory_access(&directory);
|
||||
fs::remove_dir(&directory).expect("test directory should be removed");
|
||||
let expected = if elevated {
|
||||
FILE_ALL_ACCESS
|
||||
} else {
|
||||
READ_CONTROL
|
||||
};
|
||||
assert_eq!(
|
||||
access.expect("the created directory's access should be checked"),
|
||||
(true, expected.0),
|
||||
"only elevated administrators may modify the protected directory"
|
||||
);
|
||||
}
|
||||
|
||||
fn creator_directory_access(path: &Path) -> ResultType<(bool, u32)> {
|
||||
let wide_path = wide_string(path_for_cmd_environment(path)?);
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
PCWSTR(wide_path.as_ptr()),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut descriptor,
|
||||
)
|
||||
.ok()?;
|
||||
}
|
||||
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
|
||||
let token = creator_impersonation_token()?;
|
||||
let mapping = GENERIC_MAPPING {
|
||||
GenericRead: FILE_GENERIC_READ.0,
|
||||
GenericWrite: FILE_GENERIC_WRITE.0,
|
||||
GenericExecute: FILE_GENERIC_EXECUTE.0,
|
||||
GenericAll: FILE_ALL_ACCESS.0,
|
||||
};
|
||||
let mut privileges = PRIVILEGE_SET::default();
|
||||
let mut privilege_size = mem::size_of::<PRIVILEGE_SET>() as u32;
|
||||
let mut granted = 0;
|
||||
let mut allowed = BOOL::default();
|
||||
unsafe {
|
||||
AccessCheck(
|
||||
descriptor,
|
||||
*token,
|
||||
MAXIMUM_ALLOWED,
|
||||
&mapping,
|
||||
Some(&mut privileges),
|
||||
&mut privilege_size,
|
||||
&mut granted,
|
||||
&mut allowed,
|
||||
)?;
|
||||
}
|
||||
Ok((allowed.as_bool(), granted))
|
||||
}
|
||||
|
||||
fn creator_impersonation_token() -> ResultType<Owned<HANDLE>> {
|
||||
let mut token = HANDLE::default();
|
||||
unsafe {
|
||||
OpenProcessToken(
|
||||
GetCurrentProcess(),
|
||||
TOKEN_QUERY | TOKEN_DUPLICATE,
|
||||
&mut token,
|
||||
)?
|
||||
};
|
||||
let token = unsafe { Owned::new(token) };
|
||||
let mut impersonation = HANDLE::default();
|
||||
unsafe { DuplicateToken(*token, SecurityImpersonation, &mut impersonation)? };
|
||||
Ok(unsafe { Owned::new(impersonation) })
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user