mirror of
https://github.com/winapps-org/winapps.git
synced 2026-11-29 10:55:45 -05:00
With /d:"" FreeRDP 3 tries Kerberos against the system default realm (e.g. the stock ATHENA.MIT.EDU in /etc/krb5.conf), which stalls the connection for minutes. Passing /d:. targets the local Windows account and falls back to NTLM immediately.
1162 lines
50 KiB
Bash
Executable File
1162 lines
50 KiB
Bash
Executable File
#!/usr/bin/env bash
|
||
|
||
### GLOBAL CONSTANTS ###
|
||
# ERROR CODES
|
||
readonly EC_MISSING_CONFIG=1
|
||
readonly EC_MISSING_FREERDP=2
|
||
readonly EC_NOT_IN_GROUP=3
|
||
readonly EC_FAIL_START=4
|
||
readonly EC_FAIL_RESUME=5
|
||
readonly EC_FAIL_DESTROY=6
|
||
readonly EC_SD_TIMEOUT=7
|
||
readonly EC_DIE_TIMEOUT=8
|
||
readonly EC_RESTART_TIMEOUT=9
|
||
readonly EC_NOT_EXIST=10
|
||
readonly EC_UNKNOWN=11
|
||
readonly EC_NO_IP=12
|
||
readonly EC_BAD_PORT=13
|
||
readonly EC_UNSUPPORTED_APP=14
|
||
readonly EC_INVALID_FLAVOR=15
|
||
readonly EC_INVALID_SCALE=16
|
||
|
||
# PATHS
|
||
readonly APPDATA_PATH="${HOME}/.local/share/winapps"
|
||
readonly SYS_APP_PATH="/usr/local/share/winapps"
|
||
readonly LASTRUN_PATH="${APPDATA_PATH}/lastrun"
|
||
readonly LOG_PATH="${APPDATA_PATH}/winapps.log"
|
||
readonly CONFIG_PATH="${HOME}/.config/winapps/winapps.conf"
|
||
readonly COMPOSE_PATH="${HOME}/.config/winapps/compose.yaml"
|
||
# shellcheck disable=SC2155 # Silence warnings regarding masking return values through simultaneous declaration and assignment.
|
||
readonly SCRIPT_DIR_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
|
||
readonly SLEEP_DETECT_PATH="${APPDATA_PATH}/last_activity"
|
||
readonly SLEEP_MARKER="${APPDATA_PATH}/sleep_marker"
|
||
readonly APP_ICON_PATH="${SCRIPT_DIR_PATH}/../docs/readme/winapps.svg"
|
||
|
||
# OTHER
|
||
readonly CONTAINER_NAME="WinApps" # FOR 'docker' AND 'podman' ONLY
|
||
RDP_PORT=3389
|
||
readonly DOCKER_IP="127.0.0.1"
|
||
# shellcheck disable=SC2155 # Silence warnings regarding masking return values through simultaneous declaration and assignment.
|
||
readonly RUNID="${RANDOM}"
|
||
|
||
### GLOBAL VARIABLES ###
|
||
# WINAPPS CONFIGURATION FILE
|
||
RDP_USER=""
|
||
RDP_PASS=""
|
||
RDP_ASKPASS=""
|
||
RDP_DOMAIN=""
|
||
RDP_IP=""
|
||
VM_NAME="RDPWindows" # FOR 'libvirt' ONLY
|
||
WAFLAVOR="docker"
|
||
RDP_FLAGS=""
|
||
FREERDP_COMMAND=""
|
||
REMOVABLE_MEDIA=""
|
||
RDP_SCALE=100
|
||
RDP_DEVICE_SCALE=100
|
||
# Scale for 'winapps windows'; 'inherit' uses RDP_SCALE.
|
||
RDP_DESKTOP_SCALE="inherit"
|
||
RDP_DESKTOP_DEVICE_SCALE=100
|
||
AUTOPAUSE="off"
|
||
AUTOPAUSE_TIME="300"
|
||
DEBUG="true"
|
||
BOOT_TIMEOUT=120
|
||
PORT_TIMEOUT=5
|
||
HIDEF="on"
|
||
RDP_FLATPAK=0
|
||
RDP_FLAGS_WINDOWS=""
|
||
RDP_FLAGS_NON_WINDOWS=""
|
||
|
||
# OTHER
|
||
FREERDP_PID=-1
|
||
NEEDED_BOOT=false
|
||
|
||
### TRAPS ###
|
||
# Catch SIGINT (CTRL+C) and SIGTERM to call 'waKillCleanExit'.
|
||
trap waKillCleanExit SIGINT SIGTERM
|
||
|
||
### FUNCTIONS ###
|
||
# Name: 'waCleanFreeRDP'
|
||
# Role: Clean up remains prior to exit.
|
||
function waCleanFreeRDP() {
|
||
for proc_file in "${APPDATA_PATH}"/FreeRDP_Process_*.cproc; do
|
||
# Protect against glob non-expansion.
|
||
[[ -f "$proc_file" ]] || break
|
||
|
||
# Extract the file name from the path.
|
||
cproc=$(basename "$proc_file")
|
||
|
||
# Remove the 'FreeRDP_Process_' prefix.
|
||
cproc="${cproc#FreeRDP_Process_}"
|
||
|
||
# Remove the '.cproc' file extension.
|
||
cproc="${cproc%.cproc}"
|
||
|
||
if [[ "$cproc" =~ ^[0-9]+$ ]]; then
|
||
# Proceed if process dir missing OR comm unreadable OR name doesn’t match.
|
||
if [[ ! -d "/proc/$cproc" ]] || [[ ! -r "/proc/$cproc/comm" ]] || [[ $(<"/proc/$cproc/comm") != *freerdp* ]]; then
|
||
# Delete the file.
|
||
rm -- "$proc_file" &>/dev/null
|
||
fi
|
||
elif [[ "$cproc" == "Flatpak" ]]; then
|
||
if command -v flatpak > /dev/null 2>&1; then
|
||
# Proceed if the flatpak is not running.
|
||
if ! flatpak ps --columns=application | grep -q "^com.freerdp.FreeRDP$"; then
|
||
# Delete the file.
|
||
rm -- "$proc_file" &>/dev/null
|
||
fi
|
||
fi
|
||
fi
|
||
done
|
||
}
|
||
|
||
# Name: 'waKillFreeRDP'
|
||
# Role: Kill WinApps FreeRDP sessions.
|
||
function waKillFreeRDP() {
|
||
# Declare variables.
|
||
local TERMINATED_PROCESS_IDS=()
|
||
|
||
# Loop through each matching file and add to the array.
|
||
for FREERDP_PROCESS_FILE in "${APPDATA_PATH}/FreeRDP_Process_"*.cproc; do
|
||
# Ensure the pattern is not treated as a literal string if no files match.
|
||
[[ -f "$FREERDP_PROCESS_FILE" ]] || break
|
||
|
||
# Extract the file name from the path.
|
||
FREERDP_PROCESS_FILE=$(basename "$FREERDP_PROCESS_FILE")
|
||
|
||
# Remove the 'FreeRDP_Process_' prefix.
|
||
FREERDP_PROCESS_FILE="${FREERDP_PROCESS_FILE#FreeRDP_Process_}"
|
||
|
||
# Remove the '.cproc' file extension.
|
||
FREERDP_PROCESS_FILE="${FREERDP_PROCESS_FILE%.cproc}"
|
||
|
||
# Track termination action.
|
||
KILLED=false
|
||
|
||
# Terminate processes.
|
||
if [[ "$FREERDP_PROCESS_FILE" =~ ^[0-9]+$ ]] && \
|
||
[[ -d "/proc/$FREERDP_PROCESS_FILE" ]] && \
|
||
[[ -r "/proc/$FREERDP_PROCESS_FILE/comm" ]] && \
|
||
[[ $(<"/proc/$FREERDP_PROCESS_FILE/comm") == *freerdp* ]]; then
|
||
# SIGTERM
|
||
kill -15 "$FREERDP_PROCESS_FILE" &>/dev/null
|
||
|
||
# Wait up to 5 seconds.
|
||
for _ in {1..5}; do
|
||
sleep 1
|
||
[[ ! -d "/proc/$FREERDP_PROCESS_FILE" ]] && break
|
||
done
|
||
|
||
# SIGKILL
|
||
if [[ -d "/proc/$FREERDP_PROCESS_FILE" ]] && \
|
||
[[ -r "/proc/$FREERDP_PROCESS_FILE/comm" ]] && \
|
||
[[ $(<"/proc/$FREERDP_PROCESS_FILE/comm") == *freerdp* ]]; then
|
||
kill -9 "$FREERDP_PROCESS_FILE" &>/dev/null
|
||
fi
|
||
|
||
# Track termination action.
|
||
KILLED=true
|
||
elif [[ "$FREERDP_PROCESS_FILE" == "Flatpak" ]] && \
|
||
command -v flatpak >/dev/null 2>&1 && \
|
||
flatpak ps --columns=application | grep -q "^com.freerdp.FreeRDP$"; then
|
||
# Terminate the process.
|
||
flatpak kill com.freerdp.FreeRDP &>/dev/null
|
||
|
||
# Track termination action.
|
||
KILLED=true
|
||
fi
|
||
|
||
# Delete FreeRDP process tracking file.
|
||
# NOTE: Better practice to call 'waCleanFreeRDP' to handle this in case FreeRDP process(es) still not killed.
|
||
#rm -- "${APPDATA_PATH}/FreeRDP_Process_${FREERDP_PROCESS_FILE}.cproc" &>/dev/null
|
||
|
||
if [[ "$KILLED" == true ]]; then
|
||
# Add the process ID to the list of terminated processes.
|
||
TERMINATED_PROCESS_IDS+=("$FREERDP_PROCESS_FILE")
|
||
fi
|
||
done
|
||
|
||
# Display feedback if any processes were terminated.
|
||
if [ ${#TERMINATED_PROCESS_IDS[@]} -ne 0 ]; then
|
||
dprint "KILLED FREERDP PROCESSES: $(
|
||
IFS=', '
|
||
printf '%s' "${TERMINATED_PROCESS_IDS[*]}"
|
||
)."
|
||
echo "Killed FreeRDP process(es):"
|
||
printf '%s\n' "${TERMINATED_PROCESS_IDS[@]}"
|
||
fi
|
||
}
|
||
|
||
# Name: 'waKillCleanExit'
|
||
# Role: Kill FreeRDP processes and clean process tracking files when WinApps is forcefully terminated.
|
||
function waKillCleanExit() {
|
||
# Kill FreeRDP processes.
|
||
waKillFreeRDP
|
||
|
||
# Clean orphaned files.
|
||
waCleanFreeRDP
|
||
|
||
# Terminate script.
|
||
exit 1
|
||
}
|
||
|
||
# Name: 'waEarlyDispatch'
|
||
# Role: Handle lightweight subcommands.
|
||
function waEarlyDispatch() {
|
||
if [[ -z "${1:-}" ]] || [[ "$1" == "help" ]]; then
|
||
waHelp
|
||
exit 0
|
||
elif [[ "$1" == "killrdp" ]]; then
|
||
waKillFreeRDP
|
||
waCleanFreeRDP
|
||
exit 0
|
||
elif [[ "$1" == "cleanrdp" ]]; then
|
||
waCleanFreeRDP
|
||
exit 0
|
||
fi
|
||
}
|
||
|
||
# Name: 'waThrowExit'
|
||
# Role: Throw an error message and exit the script.
|
||
function waThrowExit() {
|
||
# Declare variables.
|
||
local ERR_CODE="$1"
|
||
local INVALID_SCALE_KEY="${2:-RDP_SCALE}"
|
||
local INVALID_SCALE_VALUE="${3-$RDP_SCALE}"
|
||
|
||
# Throw error.
|
||
case "$ERR_CODE" in
|
||
"$EC_MISSING_CONFIG")
|
||
# Missing WinApps configuration file.
|
||
dprint "ERROR: MISSING WINAPPS CONFIGURATION FILE. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "The WinApps configuration file is missing.\nPlease create a WinApps configuration file at '${CONFIG_PATH}'."
|
||
;;
|
||
"$EC_MISSING_FREERDP")
|
||
dprint "ERROR: FREERDP VERSION 3 IS NOT INSTALLED. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "FreeRDP version 3 is not installed."
|
||
;;
|
||
"$EC_NOT_IN_GROUP")
|
||
dprint "ERROR: USER NOT PART OF REQUIRED GROUPS. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "The user $(whoami) is not part of the required groups.
|
||
Please run:
|
||
sudo usermod -a -G libvirt $(whoami)
|
||
sudo usermod -a -G kvm $(whoami)"
|
||
;;
|
||
"$EC_FAIL_START")
|
||
dprint "ERROR: WINDOWS FAILED TO START. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows failed to start."
|
||
;;
|
||
"$EC_FAIL_RESUME")
|
||
dprint "ERROR: WINDOWS FAILED TO RESUME. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows failed to resume."
|
||
;;
|
||
"$EC_FAIL_DESTROY")
|
||
dprint "ERROR: FAILED TO FORCE STOP WINDOWS. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Failed to forcibly stop Windows."
|
||
;;
|
||
"$EC_SD_TIMEOUT")
|
||
dprint "ERROR: WINDOWS TOOK TOO LONG TO SHUT DOWN. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows took too long to shut down."
|
||
;;
|
||
"$EC_DIE_TIMEOUT")
|
||
dprint "ERROR: WINDOWS TOOK TOO LONG TO DIE. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows took too long to die."
|
||
;;
|
||
"$EC_RESTART_TIMEOUT")
|
||
dprint "ERROR: WINDOWS TOOK TOO LONG TO RESTART. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows took too long to restart."
|
||
;;
|
||
"$EC_NOT_EXIST")
|
||
dprint "ERROR: WINDOWS NONEXISTENT. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows VM named '${VM_NAME}' does not exist."
|
||
;;
|
||
"$EC_UNKNOWN")
|
||
dprint "ERROR: UNKNOWN CONTAINER ERROR. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Unknown Windows container error."
|
||
;;
|
||
"$EC_NO_IP")
|
||
dprint "ERROR: WINDOWS UNREACHABLE. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is unreachable.\nPlease ensure Windows is assigned an IP address."
|
||
;;
|
||
"$EC_BAD_PORT")
|
||
dprint "ERROR: RDP PORT CLOSED ON '${RDP_IP}:${RDP_PORT}'. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "The Windows RDP port '${RDP_PORT}' on ip '${RDP_IP}' is closed.\nPlease ensure Remote Desktop is correctly configured on Windows."
|
||
;;
|
||
"$EC_UNSUPPORTED_APP")
|
||
dprint "ERROR: APPLICATION NOT FOUND. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Application not found.\nPlease ensure the program is correctly configured as an officially supported application."
|
||
;;
|
||
"$EC_INVALID_FLAVOR")
|
||
dprint "ERROR: INVALID FLAVOR. EXITING."
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Invalid WinApps flavor.\nPlease ensure 'docker', 'podman' or 'libvirt' are specified as the flavor in the WinApps configuration file."
|
||
;;
|
||
"$EC_INVALID_SCALE")
|
||
dprint "ERROR: ${INVALID_SCALE_KEY} MUST BE AN INTEGER. EXITING."
|
||
printf "ERROR: %s must be an integer; received '%s'.\n" "$INVALID_SCALE_KEY" "$INVALID_SCALE_VALUE" >&2
|
||
notify-send --expire-time=8000 --icon="dialog-error" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Invalid ${INVALID_SCALE_KEY} value '${INVALID_SCALE_VALUE}'.\nPlease specify an integer value."
|
||
;;
|
||
esac
|
||
|
||
# Terminate the script.
|
||
exit "$ERR_CODE"
|
||
}
|
||
|
||
# Name: 'dprint'
|
||
# Role: Conditionally print debug messages to a log file, creating it if it does not exist.
|
||
function dprint() {
|
||
[ "$DEBUG" = "true" ] && echo "[$(date)-$RUNID] $1" >>"$LOG_PATH"
|
||
}
|
||
# Name: 'waFixRemovableMedia'
|
||
# Role: If REMOVABLE_MEDIA is empty, default to /run/media (udisks default) and show a warning.
|
||
function waFixRemovableMedia() {
|
||
if [ -z "$REMOVABLE_MEDIA" ]; then
|
||
REMOVABLE_MEDIA="/run/media" # Default for udisks
|
||
dprint "NOTICE: Using default REMOVABLE_MEDIA: $REMOVABLE_MEDIA"
|
||
notify-send --expire-time=3000 --icon="drive-removable-media" \
|
||
"WinApps Notice" "Using default removable media path: $REMOVABLE_MEDIA"
|
||
fi
|
||
}
|
||
|
||
# Name: 'waHelp'
|
||
# Role: Print usage information.
|
||
function waHelp() {
|
||
local script_name
|
||
script_name="$(basename "$0")"
|
||
|
||
echo "Usage:"
|
||
echo " ${script_name} help"
|
||
echo " ${script_name} windows"
|
||
echo " ${script_name} manual <remoteapp-executable>"
|
||
echo " ${script_name} <app> [file]"
|
||
echo " ${script_name} killrdp"
|
||
echo " ${script_name} cleanrdp"
|
||
echo
|
||
|
||
echo "Commands:"
|
||
echo " help --> Show this help message."
|
||
echo " windows --> Start a full Windows desktop RDP session."
|
||
echo " manual <remoteapp-executable> --> Start a RemoteApp session for an arbitrary executable."
|
||
echo " <app> [file] --> Start a community-tested application using a preconfigured definition. Optionally open a file."
|
||
echo " killrdp --> Terminate any running WinApps FreeRDP sessions."
|
||
echo " cleanrdp --> Remove orphaned FreeRDP process tracking files."
|
||
}
|
||
|
||
# Name: 'waFixScale'
|
||
# Role: Validate the scales and choose the nearest device scales.
|
||
function waFixScale() {
|
||
local SCALE_KEY=""
|
||
local DEVICE_SCALE_KEY=""
|
||
local RAW_SCALE=""
|
||
local SCALE_DIGITS=""
|
||
local SCALE_VALUE=0
|
||
local DEVICE_SCALE=0
|
||
|
||
for SCALE_KEY in RDP_SCALE RDP_DESKTOP_SCALE; do
|
||
RAW_SCALE="${!SCALE_KEY}"
|
||
if [ "$SCALE_KEY" = "RDP_SCALE" ]; then
|
||
DEVICE_SCALE_KEY="RDP_DEVICE_SCALE"
|
||
else
|
||
DEVICE_SCALE_KEY="RDP_DESKTOP_DEVICE_SCALE"
|
||
if [ "$RAW_SCALE" = "inherit" ]; then
|
||
RAW_SCALE="$RDP_SCALE"
|
||
fi
|
||
fi
|
||
|
||
if [[ ! "$RAW_SCALE" =~ ^[+-]?[0-9]+$ ]]; then
|
||
waThrowExit "$EC_INVALID_SCALE" "$SCALE_KEY" "$RAW_SCALE"
|
||
fi
|
||
|
||
SCALE_DIGITS="${RAW_SCALE#[+-]}"
|
||
while [[ "$SCALE_DIGITS" == 0* ]] && [ "$SCALE_DIGITS" != "0" ]; do
|
||
SCALE_DIGITS="${SCALE_DIGITS#0}"
|
||
done
|
||
|
||
# Bound the value before arithmetic to avoid integer overflow.
|
||
if [[ "$RAW_SCALE" == -* ]]; then
|
||
SCALE_VALUE=0
|
||
elif (( ${#SCALE_DIGITS} > 3 )); then
|
||
SCALE_VALUE=501
|
||
else
|
||
SCALE_VALUE=$(( 10#$SCALE_DIGITS ))
|
||
fi
|
||
|
||
if (( SCALE_VALUE < 100 )); then
|
||
SCALE_VALUE=100
|
||
dprint "WARNING: ${SCALE_KEY} value '${RAW_SCALE}' is below 100. Clamping desktop scale to '${SCALE_VALUE}'."
|
||
elif (( SCALE_VALUE > 500 )); then
|
||
SCALE_VALUE=500
|
||
dprint "WARNING: ${SCALE_KEY} value '${RAW_SCALE}' is above 500. Clamping desktop scale to '${SCALE_VALUE}'."
|
||
fi
|
||
|
||
DEVICE_SCALE=$(( SCALE_VALUE <= 120 ? 100 : SCALE_VALUE <= 160 ? 140 : 180 ))
|
||
printf -v "$SCALE_KEY" '%s' "$SCALE_VALUE"
|
||
printf -v "$DEVICE_SCALE_KEY" '%s' "$DEVICE_SCALE"
|
||
if [ "$DEVICE_SCALE" != "$SCALE_VALUE" ]; then
|
||
dprint "NOTICE: Approximating the device scale for ${SCALE_KEY} from '${SCALE_VALUE}' to '${DEVICE_SCALE}'; desktop scale remains '${SCALE_VALUE}'."
|
||
fi
|
||
done
|
||
|
||
return 0
|
||
}
|
||
|
||
# Name: 'waLoadConfig'
|
||
# Role: Load the variables within the WinApps configuration file.
|
||
function waLoadConfig() {
|
||
# Load WinApps configuration file.
|
||
if [ -f "$CONFIG_PATH" ]; then
|
||
# shellcheck source=/dev/null # Exclude WinApps configuration file from being checked by ShellCheck.
|
||
source "$CONFIG_PATH"
|
||
else
|
||
waThrowExit $EC_MISSING_CONFIG
|
||
fi
|
||
|
||
RDP_PORT="${RDP_PORT:-3389}"
|
||
# An empty domain makes FreeRDP try Kerberos against the system default realm,
|
||
# which can stall the login for minutes. '.' means the local Windows account.
|
||
RDP_DOMAIN="${RDP_DOMAIN:-.}"
|
||
|
||
# Resolve RemoteApp and full-desktop scale settings.
|
||
waFixScale
|
||
# Update when $REMOVABLE_MEDIA is null
|
||
waFixRemovableMedia
|
||
# Update $AUTOPAUSE_TIME.
|
||
# RemoteApp RDP sessions take, at minimum, 20 seconds to be terminated by the Windows server.
|
||
# Hence, subtract 20 from the timeout specified by the user, as a 'built in' timeout of 20 seconds will occur.
|
||
# Source: https://techcommunity.microsoft.com/t5/security-compliance-and-identity/terminal-services-remoteapp-8482-session-termination-logic/ba-p/246566
|
||
AUTOPAUSE_TIME=$((AUTOPAUSE_TIME - 20))
|
||
AUTOPAUSE_TIME=$((AUTOPAUSE_TIME < 0 ? 0 : AUTOPAUSE_TIME))
|
||
}
|
||
|
||
# Name: 'waLastRun'
|
||
# Role: Determine the last time this script was run.
|
||
function waLastRun() {
|
||
# Declare variables.
|
||
local LAST_RUN_UNIX_TIME=0
|
||
local CURR_RUN_UNIX_TIME=0
|
||
|
||
# Store the time this script was run last as a unix timestamp.
|
||
if [ -f "$LASTRUN_PATH" ]; then
|
||
LAST_RUN_UNIX_TIME=$(stat -t -c %Y "$LASTRUN_PATH")
|
||
dprint "LAST_RUN: ${LAST_RUN_UNIX_TIME}"
|
||
fi
|
||
|
||
# Update the file modification time with the current time.
|
||
touch -- "$LASTRUN_PATH"
|
||
CURR_RUN_UNIX_TIME=$(stat -t -c %Y "$LASTRUN_PATH")
|
||
dprint "THIS_RUN: ${CURR_RUN_UNIX_TIME}"
|
||
}
|
||
|
||
# Name: 'waGetFreeRDPCommand'
|
||
# Role: Determine the correct FreeRDP command to use.
|
||
function waGetFreeRDPCommand() {
|
||
# Declare variables.
|
||
local FREERDP_MAJOR_VERSION="" # Stores the major version of the installed copy of FreeRDP.
|
||
|
||
# Attempt to set a FreeRDP command if the command variable is empty.
|
||
if [ -z "$FREERDP_COMMAND" ]; then
|
||
if [ "$1" = "windows" ] && [ "$XDG_SESSION_TYPE" = "wayland" ]; then
|
||
if command -v sdl-freerdp3 &>/dev/null; then
|
||
FREERDP_COMMAND="sdl-freerdp3"
|
||
elif command -v sdl3-freerdp &>/dev/null; then
|
||
FREERDP_COMMAND="sdl3-freerdp"
|
||
elif command -v sdl-freerdp &>/dev/null; then
|
||
FREERDP_COMMAND="sdl-freerdp"
|
||
elif command -v flatpak &>/dev/null && flatpak list --columns=application | grep -q "^com.freerdp.FreeRDP$"; then
|
||
FREERDP_COMMAND="flatpak run --command=sdl-freerdp com.freerdp.FreeRDP"
|
||
RDP_FLATPAK=1
|
||
fi
|
||
fi
|
||
|
||
# Check for 'xfreerdp'.
|
||
if [ -z "$FREERDP_COMMAND" ] && command -v xfreerdp &>/dev/null; then
|
||
# Check FreeRDP major version is 3 or greater.
|
||
FREERDP_MAJOR_VERSION=$(xfreerdp --version | head -n 1 | grep -o -m 1 '\b[0-9]\S*' | head -n 1 | cut -d'.' -f1)
|
||
if [[ $FREERDP_MAJOR_VERSION =~ ^[0-9]+$ ]] && ((FREERDP_MAJOR_VERSION >= 3)); then
|
||
FREERDP_COMMAND="xfreerdp"
|
||
fi
|
||
fi
|
||
|
||
# Check for 'xfreerdp3' command as a fallback option.
|
||
if [ -z "$FREERDP_COMMAND" ]; then
|
||
if command -v xfreerdp3 &>/dev/null; then
|
||
# Check FreeRDP major version is 3 or greater.
|
||
FREERDP_MAJOR_VERSION=$(xfreerdp3 --version | head -n 1 | grep -o -m 1 '\b[0-9]\S*' | head -n 1 | cut -d'.' -f1)
|
||
if [[ $FREERDP_MAJOR_VERSION =~ ^[0-9]+$ ]] && ((FREERDP_MAJOR_VERSION >= 3)); then
|
||
FREERDP_COMMAND="xfreerdp3"
|
||
fi
|
||
fi
|
||
fi
|
||
|
||
# Check for FreeRDP Flatpak (fallback option).
|
||
if [ -z "$FREERDP_COMMAND" ]; then
|
||
if command -v flatpak &>/dev/null; then
|
||
if flatpak list --columns=application | grep -q "^com.freerdp.FreeRDP$"; then
|
||
# Check FreeRDP major version is 3 or greater.
|
||
FREERDP_MAJOR_VERSION=$(flatpak list --columns=application,version | grep "^com.freerdp.FreeRDP" | awk '{print $2}' | cut -d'.' -f1)
|
||
if [[ $FREERDP_MAJOR_VERSION =~ ^[0-9]+$ ]] && ((FREERDP_MAJOR_VERSION >= 3)); then
|
||
FREERDP_COMMAND="flatpak run --command=xfreerdp com.freerdp.FreeRDP"
|
||
RDP_FLATPAK=1
|
||
fi
|
||
fi
|
||
fi
|
||
fi
|
||
fi
|
||
|
||
if command -v "$FREERDP_COMMAND" &>/dev/null || [ "$FREERDP_COMMAND" = "flatpak run --command=xfreerdp com.freerdp.FreeRDP" ] || [ "$FREERDP_COMMAND" = "flatpak run --command=sdl-freerdp com.freerdp.FreeRDP" ]; then
|
||
dprint "Using FreeRDP command '${FREERDP_COMMAND}'."
|
||
|
||
# Append additional flags or parameters to FreeRDP.
|
||
# These additional flags are loaded prior in 'waLoadConfig'.
|
||
[[ -n $RDP_FLAGS ]] && FREERDP_COMMAND="${FREERDP_COMMAND} ${RDP_FLAGS}"
|
||
else
|
||
waThrowExit "$EC_MISSING_FREERDP"
|
||
fi
|
||
}
|
||
|
||
# Name: 'waCheckGroupMembership'
|
||
# Role: Ensures the current user is part of the required groups.
|
||
function waCheckGroupMembership() {
|
||
# Identify groups the current user belongs to.
|
||
# shellcheck disable=SC2155 # Silence warnings regarding masking return values through simultaneous declaration and assignment.
|
||
local USER_GROUPS=$(id -nG "$(whoami)")
|
||
|
||
if ! echo "$USER_GROUPS" | grep -qE '\b(libvirt|libvirtd)\b' || \
|
||
! echo "$USER_GROUPS" | grep -qE '\bkvm\b'; then
|
||
waThrowExit "$EC_NOT_IN_GROUP"
|
||
fi
|
||
}
|
||
|
||
# Name: 'waCheckVMRunning'
|
||
# Role: Check if the Windows 'libvirt' VM is running, and attempt to start it if it is not.
|
||
function waCheckVMRunning() {
|
||
# Declare exit status variable.
|
||
local EXIT_STATUS=0
|
||
|
||
# Declare timer variables.
|
||
local TIME_ELAPSED=0
|
||
local TIME_LIMIT=60
|
||
local TIME_INTERVAL=5
|
||
|
||
# Attempt to run the Windows virtual machine.
|
||
# Note: States 'running' and 'idle' do not require intervention, and are not checked for.
|
||
if (virsh list --all --name | grep -Fxq -- "$VM_NAME"); then
|
||
if (virsh list --state-shutoff --name | grep -Fxq -- "$VM_NAME"); then
|
||
dprint "WINDOWS SHUT OFF. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
NEEDED_BOOT=true
|
||
virsh start "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_START
|
||
if (virsh list --state-paused --name | grep -Fxq -- "$VM_NAME"); then
|
||
dprint "WINDOWS PAUSED. RESUMING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Resuming Windows."
|
||
virsh resume "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_RESUME
|
||
fi
|
||
elif (virsh list --state-paused --name | grep -Fxq -- "$VM_NAME"); then
|
||
dprint "WINDOWS PAUSED. RESUMING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Resuming Windows."
|
||
virsh resume "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_RESUME
|
||
elif (virsh list --state-other --name | grep -Fxq -- "$VM_NAME"); then
|
||
if (virsh domstate "$VM_NAME" | grep -Fxq "in shutdown"); then
|
||
dprint "WINDOWS SHUTTING DOWN. WAITING."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is currently shutting down.\nIt will automatically restart once the shutdown process is complete."
|
||
EXIT_STATUS=$EC_SD_TIMEOUT
|
||
while (( TIME_ELAPSED < TIME_LIMIT )); do
|
||
if (virsh list --state-shutoff --name | grep -Fxq -- "$VM_NAME"); then
|
||
EXIT_STATUS=0
|
||
dprint "WINDOWS SHUT OFF. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
virsh start "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_START
|
||
NEEDED_BOOT=true
|
||
break
|
||
fi
|
||
sleep $TIME_INTERVAL
|
||
TIME_ELAPSED=$((TIME_ELAPSED + TIME_INTERVAL))
|
||
done
|
||
elif (virsh domstate "$VM_NAME" | grep -Fxq "crashed"); then
|
||
dprint "WINDOWS CRASHED. DESTROYING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows experienced an unexpected crash.\nAttempting to restart Windows."
|
||
virsh destroy "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_DESTROY
|
||
if [ "$EXIT_STATUS" -eq 0 ]; then
|
||
dprint "WINDOWS DESTROYED. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
virsh start "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_START
|
||
NEEDED_BOOT=true
|
||
fi
|
||
elif (virsh domstate "$VM_NAME" | grep -Fxq "dying"); then
|
||
dprint "WINDOWS DYING. WAITING."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is currently shutting down unexpectedly.\nIt will try to restart once the shutdown process finishes."
|
||
EXIT_STATUS=$EC_DIE_TIMEOUT
|
||
while (( TIME_ELAPSED < TIME_LIMIT )); do
|
||
if (virsh domstate "$VM_NAME" | grep -Fxq "crashed"); then
|
||
EXIT_STATUS=0
|
||
dprint "WINDOWS CRASHED. DESTROYING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows experienced an unexpected crash.\nAttempting to restart Windows."
|
||
virsh destroy "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_DESTROY
|
||
if [ "$EXIT_STATUS" -eq 0 ]; then
|
||
dprint "WINDOWS DESTROYED. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
virsh start "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_START
|
||
NEEDED_BOOT=true
|
||
fi
|
||
break
|
||
elif (virsh list --state-shutoff --name | grep -Fxq -- "$VM_NAME"); then
|
||
EXIT_STATUS=0
|
||
dprint "WINDOWS SHUT OFF. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
virsh start "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_START
|
||
NEEDED_BOOT=true
|
||
break
|
||
fi
|
||
sleep $TIME_INTERVAL
|
||
TIME_ELAPSED=$((TIME_ELAPSED + TIME_INTERVAL))
|
||
done
|
||
elif (virsh domstate "$VM_NAME" | grep -Fxq "pmsuspended" ); then
|
||
dprint "WINDOWS SUSPENDED. RESUMING WINDOWS."
|
||
virsh resume "$VM_NAME" &>/dev/null || EXIT_STATUS=$EC_FAIL_RESUME
|
||
fi
|
||
fi
|
||
else
|
||
EXIT_STATUS=$EC_NOT_EXIST
|
||
fi
|
||
|
||
# Handle non-zero exit statuses.
|
||
[ "$EXIT_STATUS" -ne 0 ] && waThrowExit "$EXIT_STATUS"
|
||
|
||
# Wait for VM to be fully ready
|
||
if [[ "$NEEDED_BOOT" == "true" ]]; then
|
||
dprint "WAITING FOR VM TO BE FULLY READY..."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Waiting for Windows to be ready..."
|
||
|
||
TIME_ELAPSED=0
|
||
|
||
while (( TIME_ELAPSED < BOOT_TIMEOUT )); do
|
||
# Check if VM is running
|
||
if (virsh list --state-running --name | grep -Fxq -- "$VM_NAME"); then
|
||
# libvirt: try each neighbour IP until RDP answers (ip neigh may list several)
|
||
if [[ -z "$RDP_IP" ]]; then
|
||
if waSelectReachableVMIP 1; then
|
||
dprint "VM IS READY"
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --urgency="low" "WinApps" "Windows is ready."
|
||
if [ "$NEEDED_BOOT" = "true" ]; then
|
||
sleep 10
|
||
fi
|
||
break
|
||
fi
|
||
elif timeout 1 bash -c ">/dev/tcp/$RDP_IP/$RDP_PORT" 2>/dev/null; then
|
||
dprint "VM IS READY"
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is ready."
|
||
# Add a delay after Windows is ready
|
||
if [ "$NEEDED_BOOT" = "true" ]; then
|
||
sleep 10
|
||
fi
|
||
break
|
||
fi
|
||
fi
|
||
|
||
sleep 5
|
||
TIME_ELAPSED=$((TIME_ELAPSED + 5))
|
||
|
||
# Show progress every 30 seconds
|
||
if (( TIME_ELAPSED % 30 == 0 )); then
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Still waiting for Windows to be ready... ($TIME_ELAPSED seconds elapsed)"
|
||
fi
|
||
done
|
||
|
||
# If we timed out waiting for the VM
|
||
if (( TIME_ELAPSED >= BOOT_TIMEOUT )); then
|
||
dprint "TIMEOUT WAITING FOR VM TO BE READY"
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Timeout waiting for Windows to be ready. Please try again."
|
||
waThrowExit $EC_FAIL_START
|
||
fi
|
||
fi
|
||
}
|
||
|
||
# Name: 'waCheckContainerRunning'
|
||
# Role: Throw an error if the Docker container is not running.
|
||
function waCheckContainerRunning() {
|
||
# Declare variables.
|
||
local EXIT_STATUS=0
|
||
local CONTAINER_STATE=""
|
||
local COMPOSE_COMMAND=""
|
||
local TIME_ELAPSED=0
|
||
local TIME_LIMIT=60
|
||
local TIME_INTERVAL=5
|
||
|
||
# Determine the state of the container.
|
||
CONTAINER_STATE=$("$WAFLAVOR" inspect --format='{{.State.Status}}' "$CONTAINER_NAME")
|
||
|
||
# Determine the compose command.
|
||
case "$WAFLAVOR" in
|
||
"docker") COMPOSE_COMMAND="docker compose" ;;
|
||
"podman") COMPOSE_COMMAND="podman-compose" ;;
|
||
esac
|
||
|
||
# Check container state.
|
||
# Note: Errors DO NOT result in non-zero exit statuses.
|
||
# Docker: 'created', 'restarting', 'running', 'removing', 'paused', 'exited' or 'dead'.
|
||
# Podman: 'created', 'running', 'paused', 'exited' or 'unknown'.
|
||
case "$CONTAINER_STATE" in
|
||
"created")
|
||
dprint "WINDOWS CREATED. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
$COMPOSE_COMMAND --file "$COMPOSE_PATH" start &>/dev/null
|
||
NEEDED_BOOT=true
|
||
;;
|
||
"restarting")
|
||
dprint "WINDOWS RESTARTING. WAITING."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is currently restarting. Please wait."
|
||
EXIT_STATUS=$EC_RESTART_TIMEOUT
|
||
while (( TIME_ELAPSED < TIME_LIMIT )); do
|
||
if [[ $("$WAFLAVOR" inspect --format='{{.State.Status}}' "$CONTAINER_NAME") == "running" ]]; then
|
||
EXIT_STATUS=0
|
||
dprint "WINDOWS RESTARTED."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Restarted Windows."
|
||
NEEDED_BOOT=true
|
||
break
|
||
fi
|
||
sleep $TIME_INTERVAL
|
||
TIME_ELAPSED=$((TIME_ELAPSED + TIME_INTERVAL))
|
||
done
|
||
;;
|
||
"paused")
|
||
dprint "WINDOWS PAUSED. RESUMING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Resuming Windows."
|
||
$COMPOSE_COMMAND --file "$COMPOSE_PATH" unpause &>/dev/null
|
||
;;
|
||
"exited")
|
||
dprint "WINDOWS SHUT OFF. BOOTING WINDOWS."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Booting Windows."
|
||
$COMPOSE_COMMAND --file "$COMPOSE_PATH" start &>/dev/null
|
||
NEEDED_BOOT=true
|
||
;;
|
||
"dead")
|
||
dprint "WINDOWS DEAD. RECREATING WINDOWS CONTAINER."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Re-creating and booting Windows."
|
||
$COMPOSE_COMMAND --file "$COMPOSE_PATH" down &>/dev/null && $COMPOSE_COMMAND --file "$COMPOSE_PATH" up -d &>/dev/null
|
||
NEEDED_BOOT=true
|
||
;;
|
||
"unknown")
|
||
EXIT_STATUS=$EC_UNKNOWN
|
||
;;
|
||
esac
|
||
|
||
# Handle non-zero exit statuses.
|
||
[ "$EXIT_STATUS" -ne 0 ] && waThrowExit "$EXIT_STATUS"
|
||
|
||
# Wait for container to be fully ready
|
||
if [[ "$CONTAINER_STATE" == "created" || "$CONTAINER_STATE" == "exited" || "$CONTAINER_STATE" == "dead" || "$CONTAINER_STATE" == "restarting" ]]; then
|
||
dprint "WAITING FOR CONTAINER TO BE FULLY READY..."
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Waiting for Windows to be ready..."
|
||
|
||
TIME_ELAPSED=0
|
||
|
||
while (( TIME_ELAPSED < BOOT_TIMEOUT )); do
|
||
# Check if container is running
|
||
if [[ $("$WAFLAVOR" inspect --format='{{.State.Status}}' "$CONTAINER_NAME") == "running" ]]; then
|
||
# Try to connect to RDP port to verify it's ready
|
||
if timeout 1 bash -c ">/dev/tcp/$RDP_IP/$RDP_PORT" 2>/dev/null; then
|
||
dprint "CONTAINER IS READY"
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Windows is ready."
|
||
# Add a delay after Windows is ready
|
||
if [ "$NEEDED_BOOT" = "true" ]; then
|
||
sleep 10
|
||
fi
|
||
break
|
||
fi
|
||
fi
|
||
|
||
sleep 5
|
||
TIME_ELAPSED=$((TIME_ELAPSED + 5))
|
||
|
||
# Show progress every 30 seconds
|
||
if (( TIME_ELAPSED % 30 == 0 )); then
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Still waiting for Windows to be ready... ($TIME_ELAPSED seconds elapsed)"
|
||
fi
|
||
done
|
||
|
||
# If we timed out waiting for the container
|
||
if (( TIME_ELAPSED >= BOOT_TIMEOUT )); then
|
||
dprint "TIMEOUT WAITING FOR CONTAINER TO BE READY"
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Timeout waiting for Windows to be ready. Please try again."
|
||
waThrowExit $EC_FAIL_START
|
||
fi
|
||
fi
|
||
}
|
||
|
||
# Name: 'waCheckPortOpen'
|
||
# Role: Assesses whether the RDP port on Windows is open.
|
||
function waCheckPortOpen() {
|
||
# Declare variables.
|
||
local TIME_ELAPSED=0
|
||
local TIME_LIMIT=30
|
||
local TIME_INTERVAL=5
|
||
local SELECT_STATUS=0
|
||
|
||
# Obtain Windows VM IP Address ('libvirt' ONLY)
|
||
# Note: 'RDP_IP' should not be empty if 'WAFLAVOR' is 'docker', since it is set to localhost before this function is called.
|
||
if [ -z "$RDP_IP" ] && [ "$WAFLAVOR" = "libvirt" ]; then
|
||
|
||
while (( TIME_ELAPSED < TIME_LIMIT )); do
|
||
if [ "$TIME_ELAPSED" -eq "$TIME_INTERVAL" ]; then
|
||
notify-send --expire-time=4000 --icon="dialog-info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Requesting Windows IP address..."
|
||
fi
|
||
# Try every neighbour IP for this MAC until RDP answers (see #432).
|
||
waSelectReachableVMIP 10
|
||
SELECT_STATUS=$?
|
||
if [ "$SELECT_STATUS" -eq 0 ]; then
|
||
return 0
|
||
fi
|
||
# 1 = no IP in neighbour table yet; 2 = IPs present but RDP still closed (keep waiting during boot).
|
||
sleep $TIME_INTERVAL
|
||
TIME_ELAPSED=$((TIME_ELAPSED + TIME_INTERVAL))
|
||
done
|
||
|
||
if [ "$SELECT_STATUS" -eq 2 ] || [ -n "$RDP_IP" ]; then
|
||
waThrowExit "$EC_BAD_PORT"
|
||
fi
|
||
waThrowExit "$EC_NO_IP"
|
||
fi
|
||
|
||
# Check for an open RDP port (configured / non-libvirt path).
|
||
timeout 10 nc -z "$RDP_IP" "$RDP_PORT" &>/dev/null || waThrowExit "$EC_BAD_PORT"
|
||
}
|
||
|
||
# Name: 'waSelectPodmanRoute'
|
||
# Role: Determine how FreeRDP can reach the RDP port of the Windows container.
|
||
# Note: Depending on the podman version and network backend, the RDP port is
|
||
# reachable at the container IP from within the rootless network namespace
|
||
# (netavark bridge networking), at localhost from within the rootless
|
||
# network namespace (slirp4netns port forwarding), or at localhost from
|
||
# the host network namespace (rootlessport/pasta port publishing).
|
||
# Probe these routes in order and use the first one that works, modifying
|
||
# 'RDP_IP' and 'FREERDP_COMMAND' accordingly.
|
||
function waSelectPodmanRoute() {
|
||
local CONTAINER_IP=""
|
||
CONTAINER_IP=$(podman inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$CONTAINER_NAME" 2>/dev/null)
|
||
|
||
if [ -n "$CONTAINER_IP" ] && timeout "$PORT_TIMEOUT" podman unshare --rootless-netns nc -z "$CONTAINER_IP" "$RDP_PORT" &>/dev/null; then
|
||
dprint "RDP PORT REACHABLE AT CONTAINER IP '${CONTAINER_IP}' WITHIN ROOTLESS NETWORK NAMESPACE."
|
||
RDP_IP="$CONTAINER_IP"
|
||
FREERDP_COMMAND="podman unshare --rootless-netns ${FREERDP_COMMAND}"
|
||
elif timeout "$PORT_TIMEOUT" podman unshare --rootless-netns nc -z "$RDP_IP" "$RDP_PORT" &>/dev/null; then
|
||
dprint "RDP PORT REACHABLE AT '${RDP_IP}' WITHIN ROOTLESS NETWORK NAMESPACE."
|
||
FREERDP_COMMAND="podman unshare --rootless-netns ${FREERDP_COMMAND}"
|
||
else
|
||
dprint "RDP PORT UNREACHABLE WITHIN ROOTLESS NETWORK NAMESPACE. CONNECTING FROM HOST NETWORK NAMESPACE."
|
||
waCheckPortOpen
|
||
fi
|
||
}
|
||
|
||
# Name: 'waRunCommand'
|
||
# Role: Run the requested WinApps command.
|
||
function waRunCommand() {
|
||
# Declare variables.
|
||
local ICON=""
|
||
local FILE_PATH=""
|
||
|
||
# Run option.
|
||
if [ "$1" = "windows" ]; then
|
||
# Update timeout (since there is no 'in-built' 20 second delay for full RDP sessions post-logout).
|
||
AUTOPAUSE_TIME=$((AUTOPAUSE_TIME + 20))
|
||
|
||
# Open Windows RDP session.
|
||
dprint "WINDOWS"
|
||
# shellcheck disable=SC2086 #Disable warning for globbing and word splitting
|
||
$FREERDP_COMMAND \
|
||
$RDP_FLAGS_WINDOWS \
|
||
/d:"$RDP_DOMAIN" \
|
||
/u:"$RDP_USER" \
|
||
${RDP_PASSWORD_ARG:+"$RDP_PASSWORD_ARG"} \
|
||
/scale-desktop:"$RDP_DESKTOP_SCALE" \
|
||
/scale-device:"$RDP_DESKTOP_DEVICE_SCALE" \
|
||
+auto-reconnect \
|
||
+dynamic-resolution \
|
||
/wm-class:"Microsoft Windows" \
|
||
/t:"Windows RDP Session [$RDP_IP]" \
|
||
/v:"$RDP_IP":"$RDP_PORT" &>/dev/null &
|
||
|
||
# Capture the process ID.
|
||
FREERDP_PID=$!
|
||
elif [ "$1" = "manual" ]; then
|
||
# Open specified application.
|
||
dprint "MANUAL: ${2}"
|
||
# shellcheck disable=SC2086 #Disable warning for globbing and word splitting
|
||
$FREERDP_COMMAND \
|
||
$RDP_FLAGS_NON_WINDOWS \
|
||
/d:"$RDP_DOMAIN" \
|
||
/u:"$RDP_USER" \
|
||
${RDP_PASSWORD_ARG:+"$RDP_PASSWORD_ARG"} \
|
||
/scale-desktop:"$RDP_SCALE" \
|
||
/scale-device:"$RDP_DEVICE_SCALE" \
|
||
+auto-reconnect \
|
||
/app:program:"$2",hidef:"$HIDEF" \
|
||
/v:"$RDP_IP":"$RDP_PORT" &>/dev/null &
|
||
|
||
# Capture the process ID.
|
||
FREERDP_PID=$!
|
||
else
|
||
# Script summoned from right-click menu or application icon (plus/minus a file path).
|
||
if [ -e "${SCRIPT_DIR_PATH}/../apps/${1}/info" ]; then
|
||
# shellcheck source=/dev/null # Exclude this file from being checked by ShellCheck.
|
||
source "${SCRIPT_DIR_PATH}/../apps/${1}/info"
|
||
ICON="${SCRIPT_DIR_PATH}/../apps/${1}/icon.svg"
|
||
elif [ -e "${APPDATA_PATH}/apps/${1}/info" ]; then
|
||
# shellcheck source=/dev/null # Exclude this file from being checked by ShellCheck.
|
||
source "${APPDATA_PATH}/apps/${1}/info"
|
||
ICON="${APPDATA_PATH}/apps/${1}/icon.svg"
|
||
elif [ -e "${SYS_APP_PATH}/apps/${1}/info" ]; then
|
||
# shellcheck source=/dev/null # Exclude this file from being checked by ShellCheck.
|
||
source "${SYS_APP_PATH}/apps/${1}/info"
|
||
ICON="${SYS_APP_PATH}/apps/${1}/icon.svg"
|
||
else
|
||
waThrowExit "$EC_UNSUPPORTED_APP"
|
||
fi
|
||
|
||
# Check if a file path was specified, and pass this to the application.
|
||
if [ -z "$2" ]; then
|
||
# No file path specified.
|
||
# shellcheck disable=SC2086 #Disable warning for globbing and word splitting
|
||
$FREERDP_COMMAND \
|
||
$RDP_FLAGS_NON_WINDOWS \
|
||
/d:"$RDP_DOMAIN" \
|
||
/u:"$RDP_USER" \
|
||
${RDP_PASSWORD_ARG:+"$RDP_PASSWORD_ARG"} \
|
||
/scale-desktop:"$RDP_SCALE" \
|
||
/scale-device:"$RDP_DEVICE_SCALE" \
|
||
+auto-reconnect \
|
||
/wm-class:"$FULL_NAME" \
|
||
/app:program:"$WIN_EXECUTABLE",hidef:"$HIDEF",icon:"$ICON",name:"$FULL_NAME" \
|
||
/v:"$RDP_IP":"$RDP_PORT" &>/dev/null &
|
||
|
||
# Capture the process ID.
|
||
FREERDP_PID=$!
|
||
else
|
||
# Convert path from UNIX to Windows style.
|
||
FILE_PATH=$(echo "$2" | sed \
|
||
-e 's|^'"${HOME}"'|\\\\tsclient\\home|' \
|
||
-e 's|^'"${REMOVABLE_MEDIA}"'|\\\\tsclient\\media|' \
|
||
-e 's|/|\\|g')
|
||
dprint "UNIX_FILE_PATH: ${2}"
|
||
dprint "WINDOWS_FILE_PATH: ${FILE_PATH}"
|
||
|
||
# shellcheck disable=SC2086 #Disable warning for globbing and word splitting
|
||
$FREERDP_COMMAND \
|
||
$RDP_FLAGS_NON_WINDOWS \
|
||
/d:"$RDP_DOMAIN" \
|
||
/u:"$RDP_USER" \
|
||
${RDP_PASSWORD_ARG:+"$RDP_PASSWORD_ARG"} \
|
||
/scale-desktop:"$RDP_SCALE" \
|
||
/scale-device:"$RDP_DEVICE_SCALE" \
|
||
+auto-reconnect \
|
||
/drive:media,"$REMOVABLE_MEDIA" \
|
||
/wm-class:"$FULL_NAME" \
|
||
/app:program:"$WIN_EXECUTABLE",hidef:"$HIDEF",icon:"$ICON",name:"$FULL_NAME",cmd:\""$FILE_PATH"\" \
|
||
/v:"$RDP_IP":"$RDP_PORT" &>/dev/null &
|
||
|
||
# Capture the process ID.
|
||
FREERDP_PID=$!
|
||
fi
|
||
fi
|
||
|
||
if [[ "$RDP_FLATPAK" == "0" ]]; then
|
||
if [ "$FREERDP_PID" -ne -1 ]; then
|
||
# Create a file with the process ID.
|
||
touch -- "${APPDATA_PATH}/FreeRDP_Process_${FREERDP_PID}.cproc"
|
||
|
||
# Wait for the process to terminate.
|
||
wait "$FREERDP_PID"
|
||
|
||
# Remove the file with the process ID.
|
||
rm -- "${APPDATA_PATH}/FreeRDP_Process_${FREERDP_PID}.cproc" &>/dev/null
|
||
fi
|
||
else
|
||
# Create a file.
|
||
touch -- "${APPDATA_PATH}/FreeRDP_Process_Flatpak.cproc"
|
||
|
||
# Wait for the process to terminate.
|
||
while flatpak ps --columns=application | grep -q "^com.freerdp.FreeRDP$"; do
|
||
sleep 5
|
||
done
|
||
|
||
# Remove the file.
|
||
rm -- "${APPDATA_PATH}/FreeRDP_Process_Flatpak.cproc" &>/dev/null
|
||
fi
|
||
}
|
||
|
||
# Name: 'waCheckIdle'
|
||
# Role: Suspend Windows if idle.
|
||
function waCheckIdle() {
|
||
# Declare variables
|
||
local TIME_INTERVAL=10
|
||
local TIME_ELAPSED=0
|
||
local SUSPEND_WINDOWS=0
|
||
|
||
# Prevent 'autopause' functionality with unsupported Windows backends.
|
||
if [ "$WAFLAVOR" != "manual" ]; then
|
||
# Check if there are no WinApps-related FreeRDP processes running.
|
||
if ! ls "$APPDATA_PATH"/FreeRDP_Process_*.cproc &>/dev/null; then
|
||
SUSPEND_WINDOWS=1
|
||
while (( TIME_ELAPSED < AUTOPAUSE_TIME )); do
|
||
if ls "$APPDATA_PATH"/FreeRDP_Process_*.cproc &>/dev/null; then
|
||
SUSPEND_WINDOWS=0
|
||
break
|
||
fi
|
||
sleep $TIME_INTERVAL
|
||
TIME_ELAPSED=$((TIME_ELAPSED + TIME_INTERVAL))
|
||
done
|
||
fi
|
||
|
||
# Hibernate/Pause Windows.
|
||
if [ "$SUSPEND_WINDOWS" -eq 1 ]; then
|
||
dprint "IDLE FOR ${AUTOPAUSE_TIME} SECONDS. SUSPENDING WINDOWS."
|
||
notify-send --expire-time=8000 --icon="info" --app-name="WinApps" --app-icon="$APP_ICON_PATH" --urgency="low" "WinApps" "Pausing Windows due to inactivity."
|
||
if [ "$WAFLAVOR" = "docker" ]; then
|
||
docker compose --file "$COMPOSE_PATH" pause &>/dev/null
|
||
elif [ "$WAFLAVOR" = "podman" ]; then
|
||
podman-compose --file "$COMPOSE_PATH" pause &>/dev/null
|
||
elif [ "$WAFLAVOR" = "libvirt" ]; then
|
||
virsh suspend "$VM_NAME" &>/dev/null
|
||
fi
|
||
fi
|
||
fi
|
||
}
|
||
|
||
# Name: 'waTimeSync'
|
||
# Role: Detect if system went to sleep by comparing uptime progression, then sync time in Windows VM
|
||
function waTimeSync() {
|
||
local CURRENT_TIME
|
||
local CURRENT_UPTIME
|
||
local STORED_TIME=0
|
||
local STORED_UPTIME=0
|
||
local EXPECTED_UPTIME=0
|
||
local UPTIME_DIFF=0
|
||
|
||
CURRENT_TIME=$(date +%s)
|
||
CURRENT_UPTIME=$(awk '{print int($1)}' /proc/uptime)
|
||
|
||
# Read stored values if file exists
|
||
if [ -f "$SLEEP_DETECT_PATH" ]; then
|
||
STORED_TIME=$(head -n1 "$SLEEP_DETECT_PATH" 2>/dev/null || echo 0)
|
||
STORED_UPTIME=$(tail -n1 "$SLEEP_DETECT_PATH" 2>/dev/null || echo 0)
|
||
fi
|
||
|
||
if [ "$STORED_TIME" -gt 0 ] && [ "$STORED_UPTIME" -gt 0 ]; then
|
||
# Calculate what uptime should be now
|
||
EXPECTED_UPTIME=$((STORED_UPTIME + CURRENT_TIME - STORED_TIME))
|
||
UPTIME_DIFF=$((EXPECTED_UPTIME - CURRENT_UPTIME))
|
||
|
||
dprint "UPTIME_DIFF: ${UPTIME_DIFF} seconds"
|
||
|
||
# If uptime is significantly less than expected, system likely slept
|
||
if [[ "$UPTIME_DIFF" -gt 30 && ! -f "$SLEEP_MARKER" ]]; then
|
||
dprint "DETECTED SLEEP/WAKE CYCLE (uptime gap: ${UPTIME_DIFF}s). CREATING SLEEP MARKER TO SYNC WINDOWS TIME."
|
||
|
||
# Create sleep marker which will be monitored by Windows VM to trigger time sync
|
||
touch -- "$SLEEP_MARKER"
|
||
|
||
dprint "CREATED SLEEP MARKER"
|
||
fi
|
||
fi
|
||
|
||
# Store current values
|
||
{
|
||
echo "$CURRENT_TIME"
|
||
echo "$CURRENT_UPTIME"
|
||
} > "$SLEEP_DETECT_PATH"
|
||
}
|
||
|
||
# Name: 'waFindVMIPs'
|
||
# Role: List unique IPv4 addresses associated with the Windows VM MAC in the neighbour table.
|
||
# Note: After a VM reset, 'ip neigh' can return more than one IP for the same MAC (#432).
|
||
function waFindVMIPs() {
|
||
local VM_MAC=""
|
||
|
||
VM_MAC=$(virsh domiflist "$VM_NAME" | grep -oE "([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})") # VM MAC address.
|
||
[ -z "$VM_MAC" ] && return 1
|
||
|
||
ip neigh show | grep -F -- "$VM_MAC" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | awk '!seen[$0]++'
|
||
}
|
||
|
||
# Name: 'waSelectReachableVMIP'
|
||
# Role: Try each VM neighbour IP until RDP_PORT accepts a connection; set RDP_IP on success.
|
||
# Args: $1 - timeout seconds for each nc probe (default: 10)
|
||
# Returns: 0 if a reachable IP was selected, 1 if no IPs found, 2 if all candidates failed.
|
||
function waSelectReachableVMIP() {
|
||
local port_timeout="${1:-10}"
|
||
local candidate=""
|
||
local ips=""
|
||
local tried=0
|
||
local last_ip=""
|
||
|
||
ips=$(waFindVMIPs)
|
||
if [ -z "$ips" ]; then
|
||
return 1
|
||
fi
|
||
|
||
while IFS= read -r candidate; do
|
||
[ -z "$candidate" ] && continue
|
||
tried=$((tried + 1))
|
||
last_ip="$candidate"
|
||
if timeout "$port_timeout" nc -z "$candidate" "$RDP_PORT" &>/dev/null; then
|
||
RDP_IP="$candidate"
|
||
if [ "$tried" -gt 1 ]; then
|
||
dprint "SELECTED REACHABLE VM IP '${RDP_IP}' AFTER TRYING ${tried} ADDRESS(ES)."
|
||
else
|
||
dprint "SELECTED REACHABLE VM IP '${RDP_IP}'."
|
||
fi
|
||
return 0
|
||
fi
|
||
dprint "WARNING: RDP PORT '${RDP_PORT}' CLOSED ON IP '${candidate}'. TRYING NEXT ADDRESS IF ANY."
|
||
done <<< "$ips"
|
||
|
||
# Preserve last candidate so BAD_PORT notifications can include the IP.
|
||
RDP_IP="$last_ip"
|
||
return 2
|
||
}
|
||
|
||
### MAIN LOGIC ###
|
||
#set -x # Enable for debugging.
|
||
mkdir -p "$APPDATA_PATH"
|
||
dprint "START"
|
||
dprint "SCRIPT_DIR: ${SCRIPT_DIR_PATH}"
|
||
dprint "SCRIPT_ARGS: ${*}"
|
||
dprint "HOME_DIR: ${HOME}"
|
||
waEarlyDispatch "$@"
|
||
waLastRun
|
||
waLoadConfig
|
||
waGetFreeRDPCommand "$1"
|
||
waCleanFreeRDP
|
||
|
||
# Send password on the command line if a command to retrieve the password from is not given
|
||
# Otherwise, set FREERDP_ASKPASS which freerdp will read the stdout of to use as the password
|
||
RDP_PASSWORD_ARG="/p:$RDP_PASS"
|
||
|
||
if [[ ! -z "$RDP_ASKPASS" ]]; then
|
||
export FREERDP_ASKPASS="$RDP_ASKPASS"
|
||
unset RDP_PASSWORD_ARG
|
||
fi
|
||
|
||
if [ "$WAFLAVOR" = "docker" ] || [ "$WAFLAVOR" = "podman" ]; then
|
||
RDP_IP="$DOCKER_IP"
|
||
waCheckContainerRunning
|
||
elif [ "$WAFLAVOR" = "libvirt" ]; then
|
||
waCheckGroupMembership
|
||
waCheckVMRunning
|
||
elif [ "$WAFLAVOR" = "manual" ]; then
|
||
waCheckPortOpen
|
||
else
|
||
waThrowExit "$EC_INVALID_FLAVOR"
|
||
fi
|
||
|
||
if [ "$WAFLAVOR" = "podman" ]; then
|
||
waSelectPodmanRoute
|
||
else
|
||
waCheckPortOpen
|
||
fi
|
||
waTimeSync
|
||
waRunCommand "$@"
|
||
|
||
if [[ "$AUTOPAUSE" == "on" ]]; then
|
||
waCheckIdle
|
||
fi
|
||
|
||
dprint "END"
|