Выпуск WDTT Plus v20

This commit is contained in:
Ivan4537 committed 2026-09-30 01:05:14 +03:00
1 parent ed8893a2a6
commit d450e132d2
17 files changed
+1234 -203

No files matched your search

+12
View File
@@ -2,6 +2,18 @@
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
## v20 — 30.09.2026
### Установка и управление сервером
- Исправлена подготовка страховочной копии при обновлении сервера: запись базы и статистики больше не мешает её проверке.
- Улучшено восстановление после обрыва обновления. Незавершённая копия сохраняется отдельно; повреждённые данные не используются для отката.
- Ошибка очистки страховочной копии больше не отменяет успешно проверенное обновление. Улучшены диагностика ошибок и защита от пересечения попыток деплоя.
### ВК-хеши
- Уточнён учёт результатов автополучения ВК-хешей без задержки входа и создания ссылок.
## v19 — 29.09.2026
Для новых возможностей соединения обновите серверную часть до версии 19 с сохранением данных. Приложение и сервер сохраняют совместимость с предыдущими версиями.
+4 -4
View File
@@ -46,8 +46,8 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
val appVersionName = "19"
val appVersionCode = 19
val appVersionName = "20"
val appVersionCode = 20
val releaseApkBaseName = "WDTT-Plus"
val localProperties = Properties()
@@ -105,9 +105,9 @@ android {
applicationId = "com.wdtt.plus"
minSdk = 28
targetSdk = 35
versionCode = 19
versionCode = 20
versionName = appVersionName
buildConfigField("String", "MOD_RELEASE_DATE", "\"29.09.2026\"")
buildConfigField("String", "MOD_RELEASE_DATE", "\"30.09.2026\"")
buildConfigField("boolean", "TRANSPORT_DIAGNOSTICS", transportDiagnostics.toString())
buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain))
manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain
+25 -8
View File
@@ -11,7 +11,7 @@ set -euo pipefail
readonly SCRIPT_VERSION="3.13"
readonly WDTT_DEPLOY_CONTRACT_VERSION="1"
readonly WDTT_SERVER_VERSION="19"
readonly WDTT_SERVER_VERSION="20"
readonly WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server"
readonly WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service"
readonly WDTT_ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy"
@@ -29,6 +29,7 @@ readonly MAX_HANDSHAKES="${WDTT_MAX_HANDSHAKES:-32}"
readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}"
readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}"
readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}"
readonly WDTT_DNS="${WDTT_DNS:-}"
readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}"
readonly WDTT_INSTALL_MODE="${WDTT_INSTALL_MODE:-}"
readonly WDTT_IFACE="wdtt0"
@@ -37,6 +38,7 @@ readonly WDTT_ACCESS_DB="passwords.json"
readonly WDTT_ACCESS_DB_PREVIOUS="passwords.json.previous"
readonly WDTT_WG_KEYS="wg-keys.dat"
readonly WDTT_STAGED_DB="${WDTT_STAGED_DB:-}"
readonly WDTT_STAGED_SERVER="${WDTT_STAGED_SERVER:-/tmp/wdtt-server}"
readonly IPT_COMMENT="WDTT_MANAGED"
readonly IPT_MIRROR_COMMENT="WDTT_MIRRORED"
@@ -51,6 +53,18 @@ validate_port() {
}
validate_runtime_limits() {
if [ -n "$WDTT_DNS" ]; then
[ "${#WDTT_DNS}" -le 255 ] || die "WDTT_DNS слишком длинный"
case "$WDTT_DNS" in
*[!0-9a-fA-F:.,]*|,*|*,|*,,*) die "WDTT_DNS должен содержать только адреса DNS" ;;
esac
local dns_rest="$WDTT_DNS" dns_count=1
while [ "$dns_rest" != "${dns_rest#*,}" ]; do
dns_count=$((dns_count + 1))
dns_rest="${dns_rest#*,}"
done
[ "$dns_count" -le 4 ] || die "WDTT_DNS содержит слишком много адресов"
fi
for item in \
"WDTT_MAX_PASSWORDS:$MAX_PASSWORDS" \
"WDTT_MAX_HANDSHAKES:$MAX_HANDSHAKES"; do
@@ -560,17 +574,17 @@ setup_wdtt_binary() {
prog 0.60 "Бинарник..."
echo "📦 Установка wdtt-server..."
if [ -f /tmp/wdtt-server ]; then
[ ! -L /tmp/wdtt-server ] && [ -s /tmp/wdtt-server ] || die "/tmp/wdtt-server отсутствует или небезопасен"
chmod +x /tmp/wdtt-server
if [ -f "$WDTT_STAGED_SERVER" ]; then
[ ! -L "$WDTT_STAGED_SERVER" ] && [ -s "$WDTT_STAGED_SERVER" ] || die "Загруженный wdtt-server отсутствует или небезопасен"
chmod +x "$WDTT_STAGED_SERVER"
local staged_version
staged_version="$(/tmp/wdtt-server --version 2>/dev/null | head -n 1 || true)"
staged_version="$("$WDTT_STAGED_SERVER" --version 2>/dev/null | head -n 1 || true)"
[ "$staged_version" = "$WDTT_SERVER_VERSION" ] ||
die "Загружен wdtt-server несовместимой версии: ожидается $WDTT_SERVER_VERSION, получено ${staged_version:-не определено}"
rm -f /usr/local/bin/.wdtt-server.new
install -m 0755 /tmp/wdtt-server /usr/local/bin/.wdtt-server.new || die "Не удалось подготовить новый wdtt-server"
install -m 0755 "$WDTT_STAGED_SERVER" /usr/local/bin/.wdtt-server.new || die "Не удалось подготовить новый wdtt-server"
mv -f /usr/local/bin/.wdtt-server.new /usr/local/bin/wdtt-server || die "Не удалось атомарно заменить wdtt-server"
rm -f /tmp/wdtt-server
rm -f -- "$WDTT_STAGED_SERVER"
echo "✓ wdtt-server установлен"
elif [ -f /usr/local/bin/wdtt-server ]; then
echo "✓ wdtt-server уже установлен"
@@ -604,6 +618,8 @@ setup_wdtt_service() {
echo "🔧 Создание systemd-сервиса WDTT Plus..."
local unit_tmp="/etc/systemd/system/.wdtt.service.new"
local dns_arg=""
[ -z "$WDTT_DNS" ] || dns_arg=" -dns ${WDTT_DNS}"
rm -f "$unit_tmp"
cat > "$unit_tmp" << WDTTSVC
# ${WDTT_ANDROID_DEPLOY_MARKER}
@@ -617,7 +633,7 @@ Wants=network-online.target
Type=simple
ExecStartPre=-/usr/bin/env bash -c "ip link show ${WDTT_IFACE} >/dev/null 2>&1 && ip link del ${WDTT_IFACE} 2>/dev/null || true"
ExecStartPre=-/usr/bin/env bash -c "if command -v iptables >/dev/null 2>&1; then iptables -C INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; fi"
ExecStart=${WDTT_SERVER_BINARY_PATH} -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND}
ExecStart=${WDTT_SERVER_BINARY_PATH} -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND}${dns_arg}
Restart=always
RestartSec=5
LimitNOFILE=65535
@@ -659,6 +675,7 @@ start_wdtt() {
if [ "$status" = "active" ]; then
rm -f "$WDTT_CONFIG_DIR/.android-deploy-preserved"
echo "✅ Деплой успешно завершён!"
echo "WDTT_INSTALL_RESULT=success"
echo " NAT: MASQUERADE (стандартный)"
echo " DTLS: порт ${DTLS_PORT}"
echo " WG: порт ${WG_PORT}"
+359 -162
View File
@@ -534,6 +534,8 @@ internal data class ServerUpdateRollbackMarkers(
internal sealed class ServerUpdateRollbackState {
data object None : ServerUpdateRollbackState()
data object PreparationIncomplete : ServerUpdateRollbackState()
data object Committed : ServerUpdateRollbackState()
data class PreparedValid(val markers: ServerUpdateRollbackMarkers) : ServerUpdateRollbackState()
data class PreparedCorrupted(val diagnostic: String) : ServerUpdateRollbackState()
data class UnknownState(val diagnostic: String) : ServerUpdateRollbackState()
@@ -547,6 +549,8 @@ internal fun parseServerUpdateRollbackState(output: String): ServerUpdateRollbac
.orEmpty()
return when (markerValue(output, "WDTT_UPDATE_BACKUP_STATUS")) {
"none" -> ServerUpdateRollbackState.None
"preparation_incomplete" -> ServerUpdateRollbackState.PreparationIncomplete
"committed_valid" -> ServerUpdateRollbackState.Committed
"prepared_valid" -> ServerUpdateRollbackState.PreparedValid(
ServerUpdateRollbackMarkers(
hadConfig = flag("WDTT_UPDATE_BACKUP_HAD_CONFIG"),
@@ -2137,6 +2141,8 @@ fun DeployTab(
settingsStore.recordProfileServerInstallation(checkProfile, request.host, request.sshPort, info.hasInstalledServer)
if (info.updateRollbackState !is ServerUpdateRollbackState.None) {
val validation = when (val rollback = info.updateRollbackState) {
ServerUpdateRollbackState.PreparationIncomplete -> "preparation_incomplete"
ServerUpdateRollbackState.Committed -> "committed_valid"
is ServerUpdateRollbackState.PreparedValid -> "prepared_valid"
is ServerUpdateRollbackState.PreparedCorrupted ->
"prepared_corrupted:${rollback.diagnostic}"
@@ -2147,9 +2153,7 @@ fun DeployTab(
DeployManager.writeError(
"Server update rollback backup found; validation=$validation",
)
TunnelManager.addDeployErrorLog(
"На сервере найдена страховочная копия обновления: $validation",
)
TunnelManager.addDeployErrorLog("На сервере осталось незавершённое действие обновления. Нужна проверка страховочной копии.")
pendingDeployRequest = request
existingInstallInfo = info
rollbackResolutionMessage = ""
@@ -2230,6 +2234,7 @@ fun DeployTab(
}
}
fun currentOutboundTarget(): OutboundSshTarget? {
if (!primarySshAccessReady) {
outboundStatus = primarySshAccessIssue
@@ -4325,8 +4330,8 @@ fun DeployTab(
if (deployRequest != null && installInfo != null) {
val rollbackState = installInfo.updateRollbackState
if (rollbackState !is ServerUpdateRollbackState.None) {
ServerUpdateRollbackDialog(
state = rollbackState,
ServerUpdateRollbackHost(
info = installInfo,
busy = rollbackResolutionBusy,
statusMessage = rollbackResolutionMessage,
onDismiss = {
@@ -4336,12 +4341,14 @@ fun DeployTab(
rollbackResolutionMessage = ""
}
},
onRestore = {
runRollbackResolution(ServerUpdateRollbackAction.RestorePrevious)
},
onKeepCurrent = {
runRollbackResolution(ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup)
onAction = ::runRollbackResolution,
onRetryInspection = {
pendingDeployRequest = null
existingInstallInfo = null
rollbackResolutionMessage = ""
startDeployCheck(deployRequest, requireExistingServer = true)
},
onDiagnosticStatus = { rollbackResolutionMessage = it },
)
} else {
ExistingInstallDialog(
@@ -7487,6 +7494,30 @@ private fun recordRemoteCommandEvent(event: RemoteLogEvent) {
private class SSHClient(private val session: Session, private val pass: String) {
/** Critical mutations must not mistake partial output or a nonzero remote exit for success. */
fun execChecked(command: String, timeout: Long = CMD_TIMEOUT): String {
val output = exec(command, timeout, preservePartialOnFailure = true)
if (Regex("^error:", RegexOption.MULTILINE).containsMatchIn(output)) {
val detail = serverUpdateFailureDetail(output).let {
if (pass.isNotBlank()) it.replace(pass, "[скрыто]") else it
}
DeployManager.writeError("Ошибка выполнения серверной операции:\n$detail")
throw IllegalStateException("Серверная операция не завершена:\n$detail")
}
return output
}
fun createPrivateStagingDirectory(): String {
val path = "/tmp/wdtt-deploy-${java.util.UUID.randomUUID()}"
val channel = session.openChannel("sftp") as ChannelSftp
try {
channel.connect(15_000)
channel.mkdir(path) // Refuse an existing path; do not follow/adopt it.
channel.chmod(0b111000000, path)
return path
} finally { channel.disconnect() }
}
fun exec(
command: String,
timeout: Long = CMD_TIMEOUT,
@@ -13561,7 +13592,8 @@ private fun applyServerImport(
backup: ServerBackup,
mode: ServerImportMode,
restartService: Boolean,
standaloneManaged: Boolean = false
standaloneManaged: Boolean = false,
updateAttemptId: String? = null,
) {
val currentDb = if (mode == ServerImportMode.Merge) readRemotePasswordsJson(ssh) else null
val preparedDb = normalizeDbForTarget(backup, currentDb, mode, request)
@@ -13569,10 +13601,11 @@ private fun applyServerImport(
val wgFile = File.createTempFile("wdtt-import-wg-keys-", ".dat", context.cacheDir)
val outboundFile = File.createTempFile("wdtt-import-outbound-", ".env", context.cacheDir)
val policyFile = File.createTempFile("wdtt-import-backup-policy-", ".json", context.cacheDir)
val remoteDbFile = "/tmp/wdtt-import-passwords.json"
val remoteWgFile = "/tmp/wdtt-import-wg-keys.dat"
val remoteOutboundFile = "/tmp/wdtt-import-outbound.env"
val remotePolicyFile = "/tmp/wdtt-import-backup-policy.json"
val staging = ssh.createPrivateStagingDirectory()
val remoteDbFile = "$staging/passwords.json"
val remoteWgFile = "$staging/wg-keys.dat"
val remoteOutboundFile = "$staging/outbound.env"
val remotePolicyFile = "$staging/backup-policy.json"
listOf(dbFile, wgFile, outboundFile, policyFile).forEach { file ->
file.setReadable(false, false)
file.setWritable(false, false)
@@ -13610,7 +13643,7 @@ private fun applyServerImport(
}
val command = buildString {
append("set -e; ")
append("systemctl stop wdtt 2>/dev/null || true; ")
append("wdtt_stop_service; ")
append("mkdir -p -m 700 /etc/wdtt; [ -d /etc/wdtt ] && [ ! -L /etc/wdtt ]; ")
append("install -m 600 ${shellQuote(remoteDbFile)} /etc/wdtt/.passwords.json.import; ")
append("mv -f /etc/wdtt/.passwords.json.import /etc/wdtt/passwords.json; ")
@@ -13645,7 +13678,10 @@ private fun applyServerImport(
} else {
command
}
val output = ssh.exec(rootCommand(serializedCommand), timeout = 60000L)
val guardedCommand = if (updateAttemptId != null) {
serverUpdateApplyGuardScript(serializedCommand, updateAttemptId)
} else serverUpdateShellContext() + "\nwdtt_lock\n" + serializedCommand
val output = ssh.execChecked(rootCommand(guardedCommand), timeout = SERVER_UPDATE_PREPARE_TIMEOUT_MS)
if (markerValue(output, "WDTT_IMPORT_FILES") != "1") {
throw IllegalStateException(
compactRemoteTail(output).ifBlank { "сервер не подтвердил запись импортируемых файлов" }
@@ -13677,7 +13713,7 @@ private fun applyServerImport(
} finally {
runCatching {
ssh.exec(
rootCommand("rm -f ${shellQuote(remoteDbFile)} ${shellQuote(remoteWgFile)} ${shellQuote(remoteOutboundFile)} ${shellQuote(remotePolicyFile)}"),
rootCommand("rm -f ${shellQuote(remoteDbFile)} ${shellQuote(remoteWgFile)} ${shellQuote(remoteOutboundFile)} ${shellQuote(remotePolicyFile)}; rmdir -- ${shellQuote(staging)}"),
timeout = 10_000L
)
}
@@ -13733,8 +13769,9 @@ private suspend fun performServerImportNow(
onProgress: (Float, String) -> Unit
): Boolean = withContext(Dispatchers.IO) {
var session: Session? = null
var sshClient: SSHClient? = null
var rollbackPrepared = false
var preparationStarted = false
val updateAttemptId = java.util.UUID.randomUUID().toString()
var importVerified = false
try {
onProgress(0.05f, "Подключение...")
session = createCriticalSshSession(
@@ -13750,7 +13787,6 @@ private suspend fun performServerImportNow(
)
DeployManager.activeSession = session
val ssh = SSHClient(session, request.pass)
sshClient = ssh
onProgress(0.10f, "Проверяю владельца установки...")
val ownership = deploymentOwnership(ssh)
if (ownership != DeploymentOwnership.AndroidDeploy && ownership != DeploymentOwnership.StandaloneInstaller) {
@@ -13763,16 +13799,18 @@ private suspend fun performServerImportNow(
onProgress(0.12f, "Создаю постоянную копию перед восстановлением...")
createPersistentSafetyBackup(request, "pre_restore")
onProgress(0.15f, "Проверяю текущую базу и создаю страховочную копию...")
val beforeJson = readRemotePasswordsJson(ssh)?.also {
readRemotePasswordsJson(ssh)?.also {
validatePasswordsDbStructure(JSONObject(it))
}
prepareServerUpdateRollback(ssh)
rollbackPrepared = true
preparationStarted = true
prepareServerUpdateRollback(ssh, updateAttemptId)
val beforeJson = readRemotePasswordsJson(ssh)?.also { validatePasswordsDbStructure(JSONObject(it)) }
onProgress(0.35f, "Подготовка импорта...")
applyServerImport(
context, ssh, request, backup, mode,
restartService = true,
standaloneManaged = standaloneManaged
standaloneManaged = standaloneManaged,
updateAttemptId = updateAttemptId,
)
onProgress(0.85f, "Проверяю импортированные данные и службу...")
val afterJson = readRemotePasswordsJson(ssh)
@@ -13783,17 +13821,17 @@ private suspend fun performServerImportNow(
afterJson = afterJson,
replace = mode == ServerImportMode.Replace
)
cleanupServerUpdateRollback(ssh)
rollbackPrepared = false
importVerified = true
runCatching { cleanupServerUpdateRollback(ssh, updateAttemptId) }
.onFailure { DeployManager.writeError("Импорт проверен; очистка страховочной копии не завершена: ${it.message}") }
onProgress(1.0f, "Импорт завершён")
DeployManager.stopDeploy("success")
TunnelManager.addDeploySuccessLog("Импорт состояния WDTT Plus завершён.")
true
} catch (e: Exception) {
if (rollbackPrepared) {
runCatching { sshClient?.let(::rollbackServerUpdate) }
if (preparationStarted && !importVerified) {
runCatching { recoverServerUpdateAfterFailure(session, updateAttemptId, request) }
.onFailure { rollbackError -> DeployManager.writeError("Import rollback failed: ${rollbackError.message}") }
rollbackPrepared = false
}
DeployManager.writeError("Server import critical: ${e.message}\n${e.stackTraceToString().take(500)}")
DeployManager.stopDeploy("Ошибка импорта")
@@ -13810,8 +13848,7 @@ private const val SERVER_UPDATE_BACKUP_DIR = "/var/tmp/wdtt-plus-update-backup"
internal fun serverUpdateRollbackProbeScript(
backupDir: String = SERVER_UPDATE_BACKUP_DIR,
): String = """
BACKUP=${shellQuote(backupDir)}
): String = serverUpdateShellContext(ServerUpdatePaths(backup = backupDir)) + "\n" + """
wdtt_backup_result() {
printf 'WDTT_UPDATE_BACKUP_STATUS=%s\n' "${'$'}1"
printf 'WDTT_UPDATE_BACKUP_DIAGNOSTIC=%s\n' "${'$'}2"
@@ -13823,13 +13860,31 @@ internal fun serverUpdateRollbackProbeScript(
if [ -L "${'$'}BACKUP" ] || [ ! -d "${'$'}BACKUP" ]; then
wdtt_backup_result prepared_corrupted unsafe_backup_path
fi
wdtt_private_backup || wdtt_backup_result prepared_corrupted unsafe_backup_permissions
if [ ! -f "${'$'}BACKUP/state" ] || [ -L "${'$'}BACKUP/state" ]; then
wdtt_backup_result prepared_corrupted missing_or_unsafe_state
fi
backup_state=${'$'}(cat "${'$'}BACKUP/state" 2>/dev/null || true)
if [ "${'$'}backup_state" != prepared ]; then
if [ "${'$'}backup_state" = preparing ] || [ "${'$'}backup_state" = preparation_failed ]; then
wdtt_regular "${'$'}BACKUP/format" && [ "${'$'}(cat "${'$'}BACKUP/format")" = 2 ] ||
wdtt_backup_result unknown_state unknown_preparation
wdtt_safe_tree "${'$'}BACKUP" || wdtt_backup_result prepared_corrupted unsafe_preparation
unknown=${'$'}(find "${'$'}BACKUP" -mindepth 1 -maxdepth 1 \
! -name state ! -name state.next ! -name format ! -name attempt ! -name checksums ! -name failure \
! -name config ! -name wdtt-server ! -name wdtt.service \
! -name had_config ! -name had_binary ! -name had_service \
! -name was_active ! -name was_enabled -print -quit)
[ -z "${'$'}unknown" ] || wdtt_backup_result prepared_corrupted unknown_backup_entry
wdtt_backup_result preparation_incomplete preparation_not_finished
fi
if [ "${'$'}backup_state" != prepared ] && [ "${'$'}backup_state" != applying ] &&
[ "${'$'}backup_state" != rolling_back ] && [ "${'$'}backup_state" != committed ]; then
wdtt_backup_result unknown_state state_not_prepared
fi
if [ "${'$'}backup_state" != prepared ]; then
wdtt_regular "${'$'}BACKUP/format" && [ "${'$'}(cat "${'$'}BACKUP/format")" = 2 ] ||
wdtt_backup_result unknown_state legacy_state_not_prepared
fi
for marker in had_config had_binary had_service was_active was_enabled; do
marker_path="${'$'}BACKUP/${'$'}marker"
if [ -e "${'$'}marker_path" ] || [ -L "${'$'}marker_path" ]; then
@@ -13840,7 +13895,8 @@ internal fun serverUpdateRollbackProbeScript(
if [ -f "${'$'}BACKUP/had_config" ]; then
[ -d "${'$'}BACKUP/config" ] && [ ! -L "${'$'}BACKUP/config" ] ||
wdtt_backup_result prepared_corrupted missing_config
unsafe=${'$'}(find "${'$'}BACKUP/config" -mindepth 1 \( -type l -o ! \( -type f -o -type d \) \) -print -quit 2>/dev/null || true)
unsafe=${'$'}(find "${'$'}BACKUP/config" -mindepth 1 \( -type l -o ! \( -type f -o -type d \) \) -print -quit) ||
wdtt_backup_result prepared_corrupted unreadable_config_tree
[ -z "${'$'}unsafe" ] || wdtt_backup_result prepared_corrupted unsafe_config_tree
elif [ -e "${'$'}BACKUP/config" ] || [ -L "${'$'}BACKUP/config" ]; then
wdtt_backup_result prepared_corrupted unexpected_config
@@ -13865,8 +13921,11 @@ internal fun serverUpdateRollbackProbeScript(
! -name state ! -name had_config ! -name config \
! -name had_binary ! -name wdtt-server \
! -name had_service ! -name wdtt.service \
! -name was_active ! -name was_enabled -print -quit 2>/dev/null || true)
! -name was_active ! -name was_enabled ! -name format ! -name attempt ! -name checksums \
! -name failure -print -quit)
[ -z "${'$'}unknown" ] || wdtt_backup_result prepared_corrupted unknown_backup_entry
${serverUpdateManifestProbe()}
if [ "${'$'}backup_state" = committed ]; then wdtt_backup_result committed_valid committed; fi
printf 'WDTT_UPDATE_BACKUP_STATUS=prepared_valid\n'
printf 'WDTT_UPDATE_BACKUP_DIAGNOSTIC=prepared\n'
printf 'WDTT_UPDATE_BACKUP_HAD_CONFIG=%s\n' "$([ -f "${'$'}BACKUP/had_config" ] && echo 1 || echo 0)"
@@ -13889,42 +13948,37 @@ private fun sha256File(file: File): String {
return digest.digest().joinToString("") { "%02x".format(it) }
}
private fun prepareServerUpdateRollback(ssh: SSHClient) {
val command = """
set -e
BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
[ ! -e "${'$'}BACKUP" ] || { echo WDTT_UPDATE_BACKUP=stale; exit 3; }
if [ -d /etc/wdtt ]; then
[ ! -L /etc/wdtt ] || { echo WDTT_UPDATE_BACKUP=unsafe_config; exit 4; }
unsafe=${'$'}(find /etc/wdtt -mindepth 1 \( -type l -o ! \( -type f -o -type d \) \) -print -quit 2>/dev/null || true)
[ -z "${'$'}unsafe" ] || { echo WDTT_UPDATE_BACKUP=unsafe_config; exit 4; }
fi
install -d -m 700 "${'$'}BACKUP"
if [ -d /etc/wdtt ]; then
cp -a /etc/wdtt "${'$'}BACKUP/config"
while IFS= read -r -d '' source; do
relative=${'$'}{source#/etc/wdtt/}
cmp -s "${'$'}source" "${'$'}BACKUP/config/${'$'}relative" || exit 5
done < <(find /etc/wdtt -type f -print0)
touch "${'$'}BACKUP/had_config"
fi
if [ -f /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ]; then
cp -a /usr/local/bin/wdtt-server "${'$'}BACKUP/wdtt-server"
cmp -s /usr/local/bin/wdtt-server "${'$'}BACKUP/wdtt-server" || exit 5
touch "${'$'}BACKUP/had_binary"
fi
if [ -f /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ]; then
cp -a /etc/systemd/system/wdtt.service "${'$'}BACKUP/wdtt.service"
cmp -s /etc/systemd/system/wdtt.service "${'$'}BACKUP/wdtt.service" || exit 5
touch "${'$'}BACKUP/had_service"
fi
if systemctl is-active --quiet wdtt; then touch "${'$'}BACKUP/was_active"; fi
if systemctl is-enabled --quiet wdtt; then touch "${'$'}BACKUP/was_enabled"; fi
printf 'prepared\n' > "${'$'}BACKUP/state"
chmod 600 "${'$'}BACKUP/state"
echo WDTT_UPDATE_BACKUP=ready
""".trimIndent()
val output = ssh.exec(rootCommand(command), timeout = 30000L)
private fun recoverServerUpdateAfterFailure(session: Session?, attemptId: String, request: DeployRequest) {
// One recovery connection, never a retry of install/copy. Ownership is checked again
// so a stale attempt cannot roll back another device's update.
val recoverySession = session?.takeIf { it.isConnected } ?: createCriticalSshSession(
request.host, request.user,
SshCredentials(request.pass, request.privateKey, request.keyPassphrase, request.allowPasswordAuthentication),
request.sshPort,
)
try {
val ssh = SSHClient(recoverySession, request.pass)
val own = ssh.execChecked(rootCommand(serverUpdateShellContext() + "\n" + """
if wdtt_regular "${'$'}BACKUP/attempt" && [ "${'$'}(cat "${'$'}BACKUP/attempt")" = ${shellQuote(attemptId)} ]; then
echo WDTT_UPDATE_ATTEMPT_OWNED=1
fi
""".trimIndent()), timeout = 15_000L)
if (markerValue(own, "WDTT_UPDATE_ATTEMPT_OWNED") != "1") return
when (inspectServerUpdateRollback(ssh)) {
is ServerUpdateRollbackState.PreparedValid -> rollbackServerUpdate(ssh, attemptId)
ServerUpdateRollbackState.PreparationIncomplete ->
ssh.execChecked(rootCommand(cancelServerUpdatePreparationScript(attemptId = attemptId)), timeout = SERVER_UPDATE_PREPARE_TIMEOUT_MS)
ServerUpdateRollbackState.Committed, ServerUpdateRollbackState.None -> Unit
else -> error("Страховочная копия не прошла проверку; автоматический откат запрещён")
}
} finally { if (recoverySession !== session) recoverySession.disconnect() }
}
private fun prepareServerUpdateRollback(ssh: SSHClient, attemptId: String) {
val output = ssh.execChecked(
rootCommand(prepareServerUpdateRollbackScript(attemptId = attemptId)),
timeout = SERVER_UPDATE_PREPARE_TIMEOUT_MS,
)
markerValue(output, "WDTT_UPDATE_BACKUP")?.takeIf { it != "ready" }?.let { state ->
throw IllegalStateException(
if (state == "stale") {
@@ -13948,90 +14002,39 @@ private fun inspectServerUpdateRollback(ssh: SSHClient): ServerUpdateRollbackSta
return parseServerUpdateRollbackState(output)
}
private fun cleanupServerUpdateRollback(ssh: SSHClient) {
require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) {
private fun cleanupServerUpdateRollback(ssh: SSHClient, attemptId: String) {
val state = inspectServerUpdateRollback(ssh)
require(state is ServerUpdateRollbackState.PreparedValid || state is ServerUpdateRollbackState.Committed) {
"страховочная копия изменилась или повреждена; автоматическое удаление запрещено"
}
val command = """
set -e
BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
[ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || exit 2
[ -f "${'$'}BACKUP/state" ] && [ ! -L "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || exit 2
printf 'committed\n' > "${'$'}BACKUP/state"
rm -rf "${'$'}BACKUP"
""".trimIndent()
ssh.exec(rootCommand(command), timeout = 10000L)
val command = cleanupServerUpdateBackupScript(attemptId = attemptId)
val output = ssh.execChecked(rootCommand(command), timeout = 30_000L)
check(markerValue(output, "WDTT_UPDATE_CLEANUP") == "ok") { "Удаление страховочной копии не подтверждено" }
}
private fun rollbackServerUpdate(ssh: SSHClient) {
private fun rollbackServerUpdate(ssh: SSHClient, attemptId: String? = null) {
require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) {
"страховочная копия не прошла повторную проверку; восстановление остановлено"
}
val command = """
set -e
BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
[ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || { echo WDTT_ROLLBACK=missing; exit 2; }
[ -f "${'$'}BACKUP/state" ] && [ ! -L "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || { echo WDTT_ROLLBACK=unsafe_state; exit 2; }
[ ! -e "${'$'}BACKUP/had_config" ] || { [ -d "${'$'}BACKUP/config" ] && [ ! -L "${'$'}BACKUP/config" ]; } || { echo WDTT_ROLLBACK=incomplete_config; exit 2; }
[ ! -e "${'$'}BACKUP/had_binary" ] || { [ -f "${'$'}BACKUP/wdtt-server" ] && [ ! -L "${'$'}BACKUP/wdtt-server" ]; } || { echo WDTT_ROLLBACK=incomplete_binary; exit 2; }
[ ! -e "${'$'}BACKUP/had_service" ] || { [ -f "${'$'}BACKUP/wdtt.service" ] && [ ! -L "${'$'}BACKUP/wdtt.service" ]; } || { echo WDTT_ROLLBACK=incomplete_service; exit 2; }
systemctl stop wdtt 2>/dev/null || true
if [ -f "${'$'}BACKUP/had_binary" ]; then install -m 755 "${'$'}BACKUP/wdtt-server" /usr/local/bin/wdtt-server; else rm -f /usr/local/bin/wdtt-server; fi
if [ -f "${'$'}BACKUP/had_service" ]; then install -m 644 "${'$'}BACKUP/wdtt.service" /etc/systemd/system/wdtt.service; else rm -f /etc/systemd/system/wdtt.service; fi
if [ -f "${'$'}BACKUP/had_config" ]; then rm -rf /etc/wdtt; cp -a "${'$'}BACKUP/config" /etc/wdtt; else rm -rf /etc/wdtt; fi
systemctl daemon-reload
if [ -f "${'$'}BACKUP/was_enabled" ]; then systemctl enable wdtt >/dev/null 2>&1; else systemctl disable wdtt >/dev/null 2>&1 || true; fi
if [ -f "${'$'}BACKUP/was_active" ]; then systemctl restart wdtt; sleep 2; systemctl is-active --quiet wdtt; fi
if [ -f "${'$'}BACKUP/had_binary" ]; then
[ -f /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] && [ -x /usr/local/bin/wdtt-server ] || { echo WDTT_ROLLBACK=verify_binary; exit 3; }
else
[ ! -e /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] || { echo WDTT_ROLLBACK=verify_binary_absent; exit 3; }
fi
if [ -f "${'$'}BACKUP/had_service" ]; then
[ -f /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_ROLLBACK=verify_service; exit 3; }
else
[ ! -e /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_ROLLBACK=verify_service_absent; exit 3; }
fi
if [ -f "${'$'}BACKUP/had_config" ]; then
[ -d /etc/wdtt ] && [ ! -L /etc/wdtt ] || { echo WDTT_ROLLBACK=verify_config; exit 3; }
else
[ ! -e /etc/wdtt ] && [ ! -L /etc/wdtt ] || { echo WDTT_ROLLBACK=verify_config_absent; exit 3; }
fi
if [ -f "${'$'}BACKUP/was_active" ]; then
systemctl is-active --quiet wdtt || { echo WDTT_ROLLBACK=verify_active; exit 3; }
else
! systemctl is-active --quiet wdtt || { echo WDTT_ROLLBACK=verify_inactive; exit 3; }
fi
rm -rf "${'$'}BACKUP"
echo WDTT_ROLLBACK=ok
""".trimIndent()
val output = ssh.exec(rootCommand(command), timeout = 60000L)
val command = rollbackServerUpdateScript(attemptId = attemptId)
val output = ssh.execChecked(rootCommand(command), timeout = SERVER_UPDATE_PREPARE_TIMEOUT_MS)
require(Regex("^WDTT_ROLLBACK=ok$", RegexOption.MULTILINE).containsMatchIn(output)) {
"сервер не подтвердил откат обновления"
}
}
private fun cleanupAbandonedServerUpdateRollback(ssh: SSHClient) {
require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) {
val state = inspectServerUpdateRollback(ssh)
require(state is ServerUpdateRollbackState.PreparedValid || state is ServerUpdateRollbackState.Committed) {
"страховочная копия не прошла повторную проверку; удаление запрещено"
}
val output = ssh.exec(
val output = ssh.execChecked(
rootCommand(
"""
set -e
BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
[ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || { echo WDTT_BACKUP_CLEANUP=unsafe_backup; exit 2; }
[ -f /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] && [ -x /usr/local/bin/wdtt-server ] || { echo WDTT_BACKUP_CLEANUP=missing_binary; exit 3; }
[ -f /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_BACKUP_CLEANUP=missing_service; exit 3; }
[ -f /etc/wdtt/passwords.json ] && [ ! -L /etc/wdtt/passwords.json ] && [ -s /etc/wdtt/passwords.json ] || { echo WDTT_BACKUP_CLEANUP=missing_config; exit 3; }
systemctl is-active --quiet wdtt || { echo WDTT_BACKUP_CLEANUP=service_inactive; exit 3; }
rm -rf "${'$'}BACKUP"
echo WDTT_BACKUP_CLEANUP=ok
""".trimIndent(),
cleanupServerUpdateBackupScript(),
),
timeout = 30_000L,
)
require(markerValue(output, "WDTT_BACKUP_CLEANUP") == "ok") {
require(markerValue(output, "WDTT_UPDATE_CLEANUP") == "ok") {
"текущее состояние WDTT не прошло проверку; страховочная копия сохранена"
}
}
@@ -14039,6 +14042,8 @@ private fun cleanupAbandonedServerUpdateRollback(ssh: SSHClient) {
internal enum class ServerUpdateRollbackAction {
RestorePrevious,
KeepCurrentAndDeleteBackup,
CancelPreparation,
ArchiveLegacyPreparation,
}
private suspend fun resolveServerUpdateRollback(
@@ -14048,6 +14053,8 @@ private suspend fun resolveServerUpdateRollback(
val actionName = when (action) {
ServerUpdateRollbackAction.RestorePrevious -> "restore_previous"
ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup -> "keep_current_delete_backup"
ServerUpdateRollbackAction.CancelPreparation -> "cancel_preparation"
ServerUpdateRollbackAction.ArchiveLegacyPreparation -> "archive_legacy_preparation"
}
DeployManager.writeError("Server update rollback action selected: $actionName")
var session: Session? = null
@@ -14069,6 +14076,20 @@ private suspend fun resolveServerUpdateRollback(
ServerUpdateRollbackAction.RestorePrevious -> rollbackServerUpdate(ssh)
ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup ->
cleanupAbandonedServerUpdateRollback(ssh)
ServerUpdateRollbackAction.CancelPreparation -> {
check(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparationIncomplete)
val output = ssh.execChecked(rootCommand(cancelServerUpdatePreparationScript()), timeout = SERVER_UPDATE_PREPARE_TIMEOUT_MS)
check(markerValue(output, "WDTT_UPDATE_PREPARATION") == "cancelled")
}
ServerUpdateRollbackAction.ArchiveLegacyPreparation -> {
val state = inspectServerUpdateRollback(ssh)
check(state is ServerUpdateRollbackState.PreparedCorrupted && state.diagnostic == "missing or unsafe state")
check(deploymentOwnership(ssh) in setOf(DeploymentOwnership.AndroidDeploy, DeploymentOwnership.LegacyAndroidDeploy))
val current = readRemotePasswordsJson(ssh) ?: error("Рабочая база сервера не найдена")
validatePasswordsDbForPreserving(JSONObject(current), request.mainPass)
val output = ssh.execChecked(rootCommand(archiveLegacyUpdatePreparationScript()), timeout = 30_000L)
check(markerValue(output, "WDTT_UPDATE_PREPARATION") == "archived")
}
}
check(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.None) {
"операция завершилась, но каталог страховочной копии всё ещё найден"
@@ -14079,6 +14100,10 @@ private suspend fun resolveServerUpdateRollback(
"Прежнее состояние WDTT Plus восстановлено и проверено. Страховочная копия удалена."
ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup ->
"Текущее состояние WDTT Plus проверено. Удалена только страховочная копия."
ServerUpdateRollbackAction.CancelPreparation ->
"Подготовка отменена. Состояние службы проверено; незавершённая копия сохранена отдельно. Можно повторить обновление."
ServerUpdateRollbackAction.ArchiveLegacyPreparation ->
"Рабочая установка проверена. Незавершённая копия сохранена отдельно; можно повторить обновление."
}
} catch (error: Exception) {
DeployManager.writeError(
@@ -14529,9 +14554,13 @@ private suspend fun performDeploy(
var session: Session? = null
var sshClient: SSHClient? = null
var rollbackPrepared = false
var preparationStarted = false
val updateAttemptId = java.util.UUID.randomUUID().toString()
var installationVerified = false
var preservedDbJson: String? = null
var preImportDbJson: String? = null
var stagedDatabaseFile: File? = null
var remoteStagingDirectory: String? = null
try {
onProgress(0.02f, "Подключение...")
session = createCriticalSshSession(
@@ -14614,7 +14643,7 @@ private suspend fun performDeploy(
))
) {
onProgress(0.055f, "Проверка сохранённых данных...")
val currentDbJson = readRemotePasswordsJson(ssh)?.also {
var currentDbJson = readRemotePasswordsJson(ssh)?.also {
if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) {
validatePasswordsDbStructure(JSONObject(it))
} else {
@@ -14627,13 +14656,23 @@ private suspend fun performDeploy(
"создание пустой базы вместо неизвестного состояния запрещено"
)
}
preparationStarted = true
prepareServerUpdateRollback(ssh, updateAttemptId)
rollbackPrepared = true
// The first read was preflight only. The daemon has now flushed and stopped:
// use this stable database, including its latest devices and traffic counters.
currentDbJson = readRemotePasswordsJson(ssh)?.also {
if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) validatePasswordsDbStructure(JSONObject(it))
else validatePasswordsDbForPreserving(JSONObject(it), mainPass)
}
if (mode == DeployMode.PreserveData && currentDbJson == null) {
throw IllegalStateException("После подготовки копии база сервера не найдена; обновление остановлено")
}
currentDbJsonForDeploy = currentDbJson
if (mode == DeployMode.PreserveData) {
if (importPlan == null) preservedDbJson = currentDbJson
if (importPlan?.mode == ServerImportMode.Merge) preImportDbJson = currentDbJson
}
prepareServerUpdateRollback(ssh)
rollbackPrepared = true
if (ownership == DeploymentOwnership.PreservedAndroidData) {
markPreservedAndroidData(ssh)
}
@@ -14659,9 +14698,11 @@ private suspend fun performDeploy(
}
onProgress(0.06f, "Загрузка на сервер...")
ssh.upload(scriptFile, "/tmp/deploy.sh")
ssh.upload(serverFile, "/tmp/wdtt-server")
stagedDatabaseFile?.let { ssh.upload(it, "/tmp/wdtt-passwords.json.new", permissions = 0b110000000) }
val staging = ssh.createPrivateStagingDirectory()
remoteStagingDirectory = staging
ssh.upload(scriptFile, "$staging/deploy.sh", permissions = 0b110000000)
ssh.upload(serverFile, "$staging/server", permissions = 0b111000000)
stagedDatabaseFile?.let { ssh.upload(it, "$staging/passwords.json", permissions = 0b110000000) }
scriptFile.delete()
serverFile.delete()
@@ -14673,13 +14714,15 @@ private suspend fun performDeploy(
"состояние установки изменилось после проверки; сброс остановлен"
}
assertDeploymentMayBeUpdated(resetOwnership, DeployMode.ResetAll)
ssh.exec(
ssh.execChecked(
rootCommand(
"systemctl stop wdtt 2>/dev/null || true; " +
serverUpdateApplyGuardScript(
"wdtt_stop_service; " +
"pkill -x wdtt-server 2>/dev/null || true; " +
"rm -rf /etc/wdtt; " +
"rm -f /etc/systemd/system/wdtt.service /usr/local/bin/wdtt-server; " +
"systemctl daemon-reload 2>/dev/null || true"
"systemctl daemon-reload",
updateAttemptId)
),
timeout = 30000L
)
@@ -14708,11 +14751,11 @@ private suspend fun performDeploy(
),
backup = importPlan.backup,
mode = importPlan.mode,
restartService = false
restartService = false,
updateAttemptId = updateAttemptId,
)
}
val output = ssh.exec(
rootCommand(
val installCommand =
"env WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port " +
"WDTT_INSTALL_MODE=${when (mode) {
DeployMode.FreshInstall -> "fresh"
@@ -14720,13 +14763,15 @@ private suspend fun performDeploy(
DeployMode.ResetAll -> "reset"
}} " +
"WDTT_PRESERVE_DATA=${if (mode == DeployMode.PreserveData) 1 else 0} " +
"${if (stagedDatabaseFile != null) "WDTT_STAGED_DB=/tmp/wdtt-passwords.json.new " else ""}" +
"bash /tmp/deploy.sh"
),
"WDTT_STAGED_SERVER=${shellQuote("$staging/server")} " +
"${if (stagedDatabaseFile != null) "WDTT_STAGED_DB=${shellQuote("$staging/passwords.json")} " else ""}" +
"bash ${shellQuote("$staging/deploy.sh")}"
val output = ssh.execChecked(
rootCommand(if (rollbackPrepared) serverUpdateApplyGuardScript(installCommand, updateAttemptId) else serverUpdateShellContext() + "\nwdtt_lock\n" + installCommand),
timeout = CMD_TIMEOUT
)
if (output.contains("✅") || output.contains("Деплой успешно") || output.contains("active")) {
if (markerValue(output, "WDTT_INSTALL_RESULT") == "success") {
val verifyOutput = ssh.exec(
rootCommand(
"sleep 2; printf 'BINARY=%s\\n' \"$([ -x /usr/local/bin/wdtt-server ] && echo 1 || echo 0)\"; " +
@@ -14771,9 +14816,16 @@ private suspend fun performDeploy(
replace = plan.mode == ServerImportMode.Replace
)
}
installationVerified = true
if (rollbackPrepared) {
cleanupServerUpdateRollback(ssh)
// Data, binary identity and service have been verified. Cleanup failure
// is not installation failure and must not revert a working new server.
rollbackPrepared = false
runCatching { cleanupServerUpdateRollback(ssh, updateAttemptId) }
.onFailure {
DeployManager.writeError("Обновление проверено; очистка страховочной копии не завершена: ${it.message}")
TunnelManager.addDeployMessageLog("Сервер обновлён. Очистка страховочной копии не завершена; подробности — в журнале ошибок.", warning = true)
}
}
DeployManager.installedServerVersion.value = installedServerVersion
return@withContext true
@@ -14782,12 +14834,19 @@ private suspend fun performDeploy(
throw IllegalStateException("скрипт установки вернул ошибку; подробности сохранены в errors.log")
} else {
DeployManager.writeError("Deploy unclear output: ${output.take(500)}")
throw IllegalStateException("не удалось подтвердить установку: нет признака active/успеха от скрипта")
throw IllegalStateException("не удалось подтвердить установку: нет итогового подтверждения скрипта")
}
} catch (e: Exception) {
if (rollbackPrepared) {
runCatching { sshClient?.let(::rollbackServerUpdate) }
if (preparationStarted && !installationVerified) {
runCatching {
recoverServerUpdateAfterFailure(session, updateAttemptId, DeployRequest(
host = host, user = user, pass = pass, privateKey = privateKey, keyPassphrase = keyPassphrase,
allowPasswordAuthentication = allowPasswordAuthentication, sshPort = port,
mainPass = mainPass, adminId = adminId, botToken = botToken,
dtlsPort = dtlsPort, wgPort = wgPort, localPort = localPort, dns1 = dns1, dns2 = dns2,
))
}
.onFailure { rollbackError -> DeployManager.writeError("Update rollback failed: ${rollbackError.message}") }
rollbackPrepared = false
}
@@ -14797,10 +14856,10 @@ private suspend fun performDeploy(
} finally {
stagedDatabaseFile?.delete()
runCatching {
sshClient?.exec(
rootCommand("rm -f /tmp/wdtt-server /tmp/wdtt-passwords.json.new"),
remoteStagingDirectory?.let { staging -> sshClient?.exec(
rootCommand("rm -f -- ${shellQuote("$staging/deploy.sh")} ${shellQuote("$staging/server")} ${shellQuote("$staging/passwords.json")}; rmdir -- ${shellQuote(staging)}"),
timeout = 10_000L
)
) }
}
try { session?.disconnect() } catch (_: Exception) {}
DeployManager.activeSession = null
@@ -16898,15 +16957,93 @@ private fun SelectedBackupApplyCard(
}
}
@Composable
private fun ServerUpdateRollbackHost(
info: ExistingInstallInfo,
busy: Boolean,
statusMessage: String,
onDismiss: () -> Unit,
onAction: (ServerUpdateRollbackAction) -> Unit,
onRetryInspection: () -> Unit,
onDiagnosticStatus: (String) -> Unit,
) {
ServerUpdateRollbackDialog(
info = info,
busy = busy,
statusMessage = statusMessage,
onDismiss = onDismiss,
onRestore = { onAction(ServerUpdateRollbackAction.RestorePrevious) },
onKeepCurrent = {
onAction(when (info.updateRollbackState) {
ServerUpdateRollbackState.PreparationIncomplete -> ServerUpdateRollbackAction.CancelPreparation
is ServerUpdateRollbackState.PreparedCorrupted -> ServerUpdateRollbackAction.ArchiveLegacyPreparation
else -> ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup
})
},
onRetryInspection = onRetryInspection,
onDiagnosticStatus = onDiagnosticStatus,
)
}
@Composable
private fun ServerUpdateRollbackDialog(
state: ServerUpdateRollbackState,
info: ExistingInstallInfo,
busy: Boolean,
statusMessage: String,
onDismiss: () -> Unit,
onRestore: () -> Unit,
onKeepCurrent: () -> Unit,
onRetryInspection: () -> Unit,
onDiagnosticStatus: (String) -> Unit,
) {
val state = info.updateRollbackState
val context = LocalContext.current
val scope = rememberCoroutineScope()
var reportForExport by remember(info) { mutableStateOf<String?>(null) }
val diagnosticLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("text/plain")
) { uri: Uri? ->
val report = reportForExport
reportForExport = null
if (uri == null) {
onDiagnosticStatus("Сохранение диагностики отменено.")
} else if (report == null) {
onDiagnosticStatus("Отчёт больше не доступен. Повторите сохранение.")
} else {
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
val output = context.contentResolver.openOutputStream(uri, "w")
?: error("Не удалось открыть выбранный файл")
output.bufferedWriter(Charsets.UTF_8).use { it.write(report) }
}
}.onSuccess {
onDiagnosticStatus("Диагностика сохранена в выбранный файл.")
}.onFailure {
onDiagnosticStatus("Не удалось сохранить диагностику. Выберите другой файл.")
}
}
}
}
fun saveDiagnostics() {
val snapshot = ServerUpdateDiagnosticSnapshot(
rollbackState = info.updateRollbackState,
serviceExists = info.serviceExists,
binaryExists = info.binaryExists,
configDirExists = info.configDirExists,
accessDbExists = info.accessDbExists,
wgKeysExist = info.wgKeysExist,
serviceActive = info.active,
inspectionSucceeded = info.checkError == null,
)
reportForExport = buildServerUpdateDiagnosticReport(
snapshot = snapshot,
generatedAt = Instant.now().toString(),
appVersion = BuildConfig.VERSION_NAME,
)
val filename = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT).format(Date())
diagnosticLauncher.launch("WDTT-Plus-update-diagnostic-$filename.txt")
}
val television = isTelevisionDevice()
val scrollState = rememberScrollState()
BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = { if (!busy) onDismiss() }) {
@@ -16935,10 +17072,34 @@ private fun ServerUpdateRollbackDialog(
color = MaterialTheme.colorScheme.error,
)
Text(
"Обнаружено незавершённое обновление WDTT Plus. На сервере сохранена страховочная копия предыдущего состояния.",
"На сервере остались данные предыдущей попытки обновления WDTT Plus. Приложение проверит их перед продолжением.",
style = MaterialTheme.typography.bodyMedium,
)
when (state) {
ServerUpdateRollbackState.PreparationIncomplete -> {
Text("Подготовка страховочной копии была прервана до замены сервера. Можно восстановить прежнее состояние службы и сохранить незавершённую копию отдельно. Настройки и бинарник не заменяются.")
DangerousServerHoldButton(
actionLabel = "Восстановить работу и сохранить копию отдельно",
enabled = !busy,
guardKey = "server-update-preparation-cancel",
buttonWidthFraction = 1f,
actionLabelMaxLines = 3,
onConfirmed = onKeepCurrent,
modifier = Modifier.fillMaxWidth(),
)
}
ServerUpdateRollbackState.Committed -> {
Text("Обновление было подтверждено, но удаление страховочной копии не завершилось. Приложение проверит рабочую установку перед удалением только этой копии.")
DangerousServerHoldButton(
actionLabel = "Проверить сервер и удалить копию",
enabled = !busy,
guardKey = "server-update-committed-cleanup",
buttonWidthFraction = 1f,
actionLabelMaxLines = 2,
onConfirmed = onKeepCurrent,
modifier = Modifier.fillMaxWidth(),
)
}
is ServerUpdateRollbackState.PreparedValid -> {
Surface(
shape = RoundedCornerShape(14.dp),
@@ -16985,10 +17146,24 @@ private fun ServerUpdateRollbackDialog(
}
is ServerUpdateRollbackState.PreparedCorrupted -> {
Text(
"Страховочная копия повреждена: ${state.diagnostic}. Автоматическое восстановление, удаление и обычный деплой заблокированы. Нужна ручная проверка сервера по SSH.",
"Страховочная копия неполная или не прошла проверку: ${state.diagnostic}. Восстановление и автоматическое удаление заблокированы.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
)
if (state.diagnostic == "missing or unsafe state") {
Text("Если сервер работает, приложение может проверить установку и сохранить старую незавершённую копию отдельно, не удаляя её. При небезопасной структуре действие будет остановлено.", style = MaterialTheme.typography.bodySmall)
DangerousServerHoldButton(
actionLabel = "Проверить сервер и сохранить копию отдельно",
enabled = !busy,
guardKey = "server-update-legacy-preparation-archive",
buttonWidthFraction = 1f,
actionLabelMaxLines = 3,
onConfirmed = onKeepCurrent,
modifier = Modifier.fillMaxWidth(),
)
} else {
Text("Нужна ручная проверка сервера по SSH.", style = MaterialTheme.typography.bodySmall)
}
}
is ServerUpdateRollbackState.UnknownState -> {
Text(
@@ -16999,6 +17174,28 @@ private fun ServerUpdateRollbackDialog(
}
ServerUpdateRollbackState.None -> Unit
}
if (state is ServerUpdateRollbackState.PreparedCorrupted ||
state is ServerUpdateRollbackState.UnknownState
) {
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
Text(
"Без изменений на сервере",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedButton(
onClick = onRetryInspection,
enabled = !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
shape = RoundedCornerShape(16.dp),
) { Text("Повторить проверку") }
OutlinedButton(
onClick = ::saveDiagnostics,
enabled = !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
shape = RoundedCornerShape(16.dp),
) { Text("Сохранить диагностику") }
}
if (busy) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
@@ -0,0 +1,73 @@
package com.wdtt.plus.ui
import java.util.Locale
/** Only public, bounded inspection results belong in a support report. */
internal data class ServerUpdateDiagnosticSnapshot(
val rollbackState: ServerUpdateRollbackState,
val serviceExists: Boolean,
val binaryExists: Boolean,
val configDirExists: Boolean,
val accessDbExists: Boolean,
val wgKeysExist: Boolean,
val serviceActive: Boolean,
val inspectionSucceeded: Boolean,
)
private val knownRollbackDiagnostics = setOf(
"absent", "checksum_mismatch", "committed", "invalid_format",
"legacy_state_not_prepared", "missing_binary", "missing_checksums",
"missing_config", "missing_format", "missing_or_unsafe_state",
"missing_service", "preparation_not_finished", "state_not_prepared",
"unknown_backup_entry", "unknown_preparation", "unreadable_backup",
"unreadable_checksums", "unreadable_config_tree", "unsafe_backup_path",
"unsafe_backup_permissions", "unsafe_config_tree", "unsafe_marker",
"unsafe_preparation", "unexpected_binary", "unexpected_config",
"unexpected_service", "service_state_without_service",
)
private fun safeRollbackDiagnostic(value: String): String {
val code = value.trim().lowercase(Locale.ROOT).replace(' ', '_')
return code.takeIf(knownRollbackDiagnostics::contains) ?: "other"
}
internal fun buildServerUpdateDiagnosticReport(
snapshot: ServerUpdateDiagnosticSnapshot,
generatedAt: String,
appVersion: String,
): String {
val (state, detail) = when (val rollback = snapshot.rollbackState) {
ServerUpdateRollbackState.None -> "none" to "absent"
ServerUpdateRollbackState.PreparationIncomplete -> "preparation_incomplete" to "preparation_not_finished"
ServerUpdateRollbackState.Committed -> "committed_valid" to "committed"
is ServerUpdateRollbackState.PreparedValid -> "prepared_valid" to "verified"
is ServerUpdateRollbackState.PreparedCorrupted ->
"prepared_corrupted" to safeRollbackDiagnostic(rollback.diagnostic)
is ServerUpdateRollbackState.UnknownState ->
"unknown_state" to safeRollbackDiagnostic(rollback.diagnostic)
}
fun flag(value: Boolean) = if (value) "yes" else "no"
return buildString {
appendLine("WDTT Plus — диагностика обновления сервера")
appendLine("Создано: $generatedAt")
appendLine("Версия приложения: $appVersion")
appendLine("Данные: только результат последней проверки, без адреса сервера и секретов")
appendLine("Проверка SSH завершена: ${flag(snapshot.inspectionSucceeded)}")
appendLine("Состояние страховочной копии: $state")
appendLine("Код проверки копии: $detail")
appendLine("Служба активна: ${flag(snapshot.serviceActive)}")
appendLine("Unit-файл обнаружен: ${flag(snapshot.serviceExists)}")
appendLine("Бинарник обнаружен: ${flag(snapshot.binaryExists)}")
appendLine("Каталог конфигурации обнаружен: ${flag(snapshot.configDirExists)}")
appendLine("База доступа обнаружена: ${flag(snapshot.accessDbExists)}")
appendLine("Ключи WireGuard обнаружены: ${flag(snapshot.wgKeysExist)}")
if (snapshot.rollbackState is ServerUpdateRollbackState.PreparedValid) {
val markers = snapshot.rollbackState.markers
appendLine("Копия конфигурации: ${flag(markers.hadConfig)}")
appendLine("Копия бинарника: ${flag(markers.hadBinary)}")
appendLine("Копия unit-файла: ${flag(markers.hadService)}")
appendLine("Служба была активна до обновления: ${flag(markers.wasActive)}")
appendLine("Служба была включена до обновления: ${flag(markers.wasEnabled)}")
}
}
}
@@ -0,0 +1,328 @@
package com.wdtt.plus.ui
/** Paths are injectable only for host-free shell tests; production uses the canonical paths. */
internal data class ServerUpdatePaths(
val backup: String = "/var/tmp/wdtt-plus-update-backup",
val config: String = "/etc/wdtt",
val binary: String = "/usr/local/bin/wdtt-server",
val unit: String = "/etc/systemd/system/wdtt.service",
val lock: String = "/run/lock/wdtt-plus-update.lock",
)
internal const val SERVER_UPDATE_PREPARE_TIMEOUT_MS = 180_000L
private fun updateQuote(value: String) = "'" + value.replace("'", "'\"'\"'") + "'"
internal fun serverUpdateShellContext(paths: ServerUpdatePaths = ServerUpdatePaths()): String = """
set -euo pipefail
umask 077
BACKUP=${updateQuote(paths.backup)}
CONFIG=${updateQuote(paths.config)}
BINARY=${updateQuote(paths.binary)}
UNIT=${updateQuote(paths.unit)}
LOCK=${updateQuote(paths.lock)}
wdtt_lock() {
command -v flock >/dev/null || { echo 'error: для безопасного обновления требуется flock'; exit 2; }
[ ! -L "${'$'}LOCK" ] || { echo 'error: небезопасный файл блокировки обновления'; exit 2; }
if [ ! -e "${'$'}LOCK" ]; then
# Atomic exclusive creation; never truncate an existing path in a
# shared lock directory, including one created between these checks.
(set -C; : > "${'$'}LOCK") 2>/dev/null || true
fi
wdtt_regular "${'$'}LOCK" && [ "${'$'}(stat -c %u "${'$'}LOCK")" = "${'$'}(id -u)" ] &&
[ "${'$'}(stat -c %h "${'$'}LOCK")" = 1 ] || exit 2
exec 9<"${'$'}LOCK"
flock -n 9 || { echo 'error: другая операция обновления ещё выполняется'; exit 2; }
}
wdtt_update_phase() {
printf '%s\n' "${'$'}1" > "${'$'}BACKUP/state.next"
mv -f -- "${'$'}BACKUP/state.next" "${'$'}BACKUP/state"
}
wdtt_regular() { [ -f "${'$'}1" ] && [ ! -L "${'$'}1" ]; }
wdtt_private_backup() {
[ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] &&
[ "${'$'}(stat -c %u "${'$'}BACKUP")" = "${'$'}(id -u)" ] &&
[ "${'$'}(stat -c %a "${'$'}BACKUP")" = 700 ]
}
wdtt_safe_tree() {
[ -d "${'$'}1" ] && [ ! -L "${'$'}1" ] || return 1
local unsafe
unsafe=${'$'}(find "${'$'}1" -mindepth 1 \( -type l -o ! \( -type f -o -type d \) \) -print -quit) || return 1
[ -z "${'$'}unsafe" ]
}
wdtt_manifest() {
(cd "${'$'}BACKUP"; find . -mindepth 1 -type f \
! -path ./state ! -path ./state.next ! -path ./checksums \
! -path ./failure -print0 | LC_ALL=C sort -z | xargs -0 -r sha256sum --)
}
wdtt_quarantine() {
local destination
destination=${'$'}(mktemp -d "${'$'}{BACKUP}.incomplete.XXXXXX")
mv -T -- "${'$'}BACKUP" "${'$'}destination/copy"
printf 'WDTT_UPDATE_ARCHIVE=%s\n' "${'$'}destination"
}
wdtt_discard_backup() {
local destination
destination=${'$'}(mktemp -d "${'$'}{BACKUP}.completed.XXXXXX")
mv -T -- "${'$'}BACKUP" "${'$'}destination/copy"
rm -rf -- "${'$'}destination"
}
wdtt_stop_service() {
if ! systemctl stop wdtt; then
[ "${'$'}(systemctl show -p LoadState --value wdtt)" = not-found ] &&
! systemctl is-active --quiet wdtt && command -v pgrep >/dev/null &&
! pgrep -x wdtt-server >/dev/null || return 1
fi
! systemctl is-active --quiet wdtt
}
""".trimIndent()
/** A stopped daemon cannot rewrite passwords.json/server.log between copy and comparison. */
internal fun prepareServerUpdateRollbackScript(
paths: ServerUpdatePaths = ServerUpdatePaths(),
attemptId: String = java.util.UUID.randomUUID().toString(),
): String =
serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
[ ! -e "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || { echo WDTT_UPDATE_BACKUP=stale; exit 3; }
stage=preflight
for tool in cp cmp diff sha256sum find sort xargs stat mktemp du df awk; do
command -v "${'$'}tool" >/dev/null || { printf 'error: для безопасного обновления требуется %s\n' "${'$'}tool"; exit 4; }
done
[ ! -e "${'$'}CONFIG" ] || wdtt_safe_tree "${'$'}CONFIG" || { echo 'error: небезопасная конфигурация'; exit 4; }
[ ! -L "${'$'}CONFIG" ] || exit 4
for path in "${'$'}BINARY" "${'$'}UNIT"; do
[ ! -e "${'$'}path" ] && [ ! -L "${'$'}path" ] || wdtt_regular "${'$'}path" || exit 4
done
# Refuse an obviously impossible snapshot before interrupting a healthy service.
# This is only preflight; a later ENOSPC is still handled by the preparation trap.
required_kib=32768
for path in "${'$'}CONFIG" "${'$'}BINARY" "${'$'}UNIT"; do
if [ -e "${'$'}path" ]; then
size_kib=${'$'}(du -sk -- "${'$'}path" | awk '{print ${'$'}1}')
[[ "${'$'}size_kib" =~ ^[0-9]+${'$'} ]] || exit 4
required_kib=${'$'}((required_kib + size_kib))
fi
done
available_kib=${'$'}(df -Pk -- "${'$'}(dirname "${'$'}BACKUP")" | awk 'NR==2 {print ${'$'}4}')
[[ "${'$'}available_kib" =~ ^[0-9]+${'$'} ]] && [ "${'$'}available_kib" -ge "${'$'}required_kib" ] || {
echo 'error: недостаточно свободного места для полной страховочной копии'; exit 4;
}
install -d -m 700 "${'$'}BACKUP"
ready=0
wdtt_prepare_exit() {
local status=${'$'}?
trap - EXIT HUP INT TERM
if [ "${'$'}ready" = 0 ]; then
set +e
printf '%s\n' "${'$'}stage" > "${'$'}BACKUP/failure"
wdtt_update_phase preparation_failed
restored=1
if [ -f "${'$'}BACKUP/was_active" ]; then
systemctl start wdtt && systemctl is-active --quiet wdtt || restored=0
fi
if [ "${'$'}restored" = 1 ]; then wdtt_quarantine; fi
printf 'error: подготовка страховочной копии остановлена на этапе %s (код %s)\n' "${'$'}stage" "${'$'}status"
[ "${'$'}status" != 0 ] || status=1
fi
exit "${'$'}status"
}
trap wdtt_prepare_exit EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
stage=journal
printf '2\n' > "${'$'}BACKUP/format"
printf '%s\n' ${updateQuote(attemptId)} > "${'$'}BACKUP/attempt"
wdtt_update_phase preparing
stage=service_state
if systemctl is-active --quiet wdtt; then
wdtt_regular "${'$'}UNIT" || exit 4
touch "${'$'}BACKUP/was_active"
fi
if systemctl is-enabled --quiet wdtt; then touch "${'$'}BACKUP/was_enabled"; fi
stage=stop_service
if [ -f "${'$'}BACKUP/was_active" ]; then
printf 'WDTT_PROGRESS|0.057|Создаю согласованную копию. Служба WDTT приостановлена на время обновления…\n'
fi
# Also stop an inactive/starting unit: it must not activate during copying.
wdtt_stop_service || exit 5
stage=copy_config
if [ -d "${'$'}CONFIG" ]; then
cp -a -- "${'$'}CONFIG" "${'$'}BACKUP/config"
wdtt_safe_tree "${'$'}BACKUP/config" || exit 5
stage=verify_config
# Compare in both directions: missing or extra files/directories are also a failure.
diff -qr -- "${'$'}CONFIG" "${'$'}BACKUP/config" >/dev/null || exit 5
touch "${'$'}BACKUP/had_config"
fi
stage=copy_binary
if wdtt_regular "${'$'}BINARY"; then
cp -a -- "${'$'}BINARY" "${'$'}BACKUP/wdtt-server"
cmp -s -- "${'$'}BINARY" "${'$'}BACKUP/wdtt-server" || exit 5
touch "${'$'}BACKUP/had_binary"
fi
stage=copy_unit
if wdtt_regular "${'$'}UNIT"; then
cp -a -- "${'$'}UNIT" "${'$'}BACKUP/wdtt.service"
cmp -s -- "${'$'}UNIT" "${'$'}BACKUP/wdtt.service" || exit 5
touch "${'$'}BACKUP/had_service"
fi
stage=manifest
wdtt_manifest > "${'$'}BACKUP/checksums"
stage=publish
wdtt_update_phase prepared
ready=1
echo WDTT_UPDATE_BACKUP=ready
""".trimIndent()
internal fun serverUpdateManifestProbe(): String = """
if [ -e "${'$'}BACKUP/format" ] || [ -L "${'$'}BACKUP/format" ]; then
wdtt_regular "${'$'}BACKUP/format" && [ "${'$'}(cat "${'$'}BACKUP/format")" = 2 ] ||
wdtt_backup_result prepared_corrupted invalid_format
wdtt_regular "${'$'}BACKUP/checksums" || wdtt_backup_result prepared_corrupted missing_checksums
expected=${'$'}(cat "${'$'}BACKUP/checksums") || wdtt_backup_result prepared_corrupted unreadable_checksums
actual=${'$'}(wdtt_manifest) || wdtt_backup_result prepared_corrupted unreadable_backup
[ "${'$'}expected" = "${'$'}actual" ] || wdtt_backup_result prepared_corrupted checksum_mismatch
elif [ -e "${'$'}BACKUP/checksums" ] || [ -L "${'$'}BACKUP/checksums" ] ||
[ -e "${'$'}BACKUP/attempt" ] || [ -L "${'$'}BACKUP/attempt" ]; then
wdtt_backup_result prepared_corrupted missing_format
fi
""".trimIndent()
/** Interrupted preparation has not changed the installation; never restore a partial config. */
internal fun cancelServerUpdatePreparationScript(
paths: ServerUpdatePaths = ServerUpdatePaths(),
attemptId: String? = null,
): String =
serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
${attemptId?.let(::serverUpdateAttemptGuard).orEmpty()}
wdtt_private_backup || exit 2
wdtt_safe_tree "${'$'}BACKUP" || exit 2
wdtt_regular "${'$'}BACKUP/format" && [ "${'$'}(cat "${'$'}BACKUP/format")" = 2 ] || exit 2
wdtt_regular "${'$'}BACKUP/state" || exit 2
case "${'$'}(cat "${'$'}BACKUP/state")" in preparing|preparation_failed) ;; *) exit 2 ;; esac
wdtt_regular "${'$'}BINARY" && [ -x "${'$'}BINARY" ] && wdtt_regular "${'$'}UNIT" || exit 3
wdtt_regular "${'$'}CONFIG/passwords.json" && [ -s "${'$'}CONFIG/passwords.json" ] || exit 3
if [ -f "${'$'}BACKUP/was_active" ]; then
systemctl start wdtt
systemctl is-active --quiet wdtt || exit 3
fi
wdtt_quarantine
echo WDTT_UPDATE_PREPARATION=cancelled
""".trimIndent()
internal fun serverUpdateApplyGuardScript(
command: String,
attemptId: String,
paths: ServerUpdatePaths = ServerUpdatePaths(),
): String =
serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
wdtt_regular "${'$'}BACKUP/state" || exit 2
case "${'$'}(cat "${'$'}BACKUP/state")" in prepared|applying) ;; *) exit 2 ;; esac
wdtt_regular "${'$'}BACKUP/attempt" && [ "${'$'}(cat "${'$'}BACKUP/attempt")" = ${updateQuote(attemptId)} ] || exit 2
probe=${'$'}( (${serverUpdateRollbackProbeScript(paths.backup)}) )
printf '%s\n' "${'$'}probe" | grep -qx 'WDTT_UPDATE_BACKUP_STATUS=prepared_valid' || exit 2
wdtt_update_phase applying
""".trimIndent() + "\n" + command
internal fun serverUpdateAttemptGuard(attemptId: String): String = """
wdtt_regular "${'$'}BACKUP/attempt" && [ "${'$'}(cat "${'$'}BACKUP/attempt")" = ${updateQuote(attemptId)} ] || exit 2
""".trimIndent()
internal fun serverUpdateFailureDetail(output: String): String =
redactRemoteDiagnostics(output).lineSequence()
.filter { it.isNotBlank() && !it.startsWith("WDTT_PROGRESS|") }
.takeLastLines(12).joinToString("\n").takeLast(3000)
private fun Sequence<String>.takeLastLines(count: Int): List<String> {
val lines = ArrayDeque<String>()
for (line in this) { if (lines.size == count) lines.removeFirst(); lines.addLast(line) }
return lines.toList()
}
/** Explicit recovery for the old config-only, unmarked preparation failure; never delete it. */
internal fun archiveLegacyUpdatePreparationScript(paths: ServerUpdatePaths = ServerUpdatePaths()): String =
serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
wdtt_private_backup || exit 2
wdtt_safe_tree "${'$'}BACKUP" && wdtt_safe_tree "${'$'}BACKUP/config" || exit 2
[ ! -e "${'$'}BACKUP/state" ] && [ ! -L "${'$'}BACKUP/state" ] || exit 2
unknown=${'$'}(find "${'$'}BACKUP" -mindepth 1 -maxdepth 1 ! -name config -print -quit)
[ -z "${'$'}unknown" ] || exit 2
wdtt_regular "${'$'}BINARY" && [ -x "${'$'}BINARY" ] && wdtt_regular "${'$'}UNIT" || exit 3
wdtt_regular "${'$'}CONFIG/passwords.json" && [ -s "${'$'}CONFIG/passwords.json" ] || exit 3
systemctl is-active --quiet wdtt || exit 3
wdtt_quarantine
echo WDTT_UPDATE_PREPARATION=archived
""".trimIndent()
internal fun cleanupServerUpdateBackupScript(
paths: ServerUpdatePaths = ServerUpdatePaths(),
attemptId: String? = null,
): String = serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
${attemptId?.let(::serverUpdateAttemptGuard).orEmpty()}
probe=${'$'}( (${serverUpdateRollbackProbeScript(paths.backup)}) )
printf '%s\n' "${'$'}probe" | grep -Eq '^WDTT_UPDATE_BACKUP_STATUS=(prepared_valid|committed_valid)$' || exit 2
wdtt_regular "${'$'}BINARY" && [ -x "${'$'}BINARY" ] && wdtt_regular "${'$'}UNIT" || exit 3
wdtt_regular "${'$'}CONFIG/passwords.json" && [ -s "${'$'}CONFIG/passwords.json" ] || exit 3
systemctl is-active --quiet wdtt || exit 3
if [ -f "${'$'}BACKUP/format" ]; then wdtt_update_phase committed; fi
# Move atomically out of the recovery path first. Interruption during deletion
# cannot turn a successfully committed update into an incomplete active backup.
wdtt_discard_backup
echo WDTT_UPDATE_CLEANUP=ok
""".trimIndent()
internal fun rollbackServerUpdateScript(
paths: ServerUpdatePaths = ServerUpdatePaths(),
attemptId: String? = null,
): String = serverUpdateShellContext(paths) + "\n" + """
wdtt_lock
${attemptId?.let(::serverUpdateAttemptGuard).orEmpty()}
probe=${'$'}( (${serverUpdateRollbackProbeScript(paths.backup)}) )
printf '%s\n' "${'$'}probe" | grep -qx 'WDTT_UPDATE_BACKUP_STATUS=prepared_valid' || exit 2
[ ! -L "${'$'}CONFIG" ] && [ ! -L "${'$'}BINARY" ] && [ ! -L "${'$'}UNIT" ] || exit 3
wdtt_safe_tree "${'$'}BACKUP" || exit 3
if [ -f "${'$'}BACKUP/format" ]; then wdtt_update_phase rolling_back; fi
wdtt_stop_service || exit 3
if [ -f "${'$'}BACKUP/had_binary" ]; then
install -m 755 "${'$'}BACKUP/wdtt-server" "${'$'}BINARY"
cmp -s "${'$'}BACKUP/wdtt-server" "${'$'}BINARY" || exit 3
else rm -f -- "${'$'}BINARY"; fi
if [ -f "${'$'}BACKUP/had_service" ]; then
install -m 644 "${'$'}BACKUP/wdtt.service" "${'$'}UNIT"
cmp -s "${'$'}BACKUP/wdtt.service" "${'$'}UNIT" || exit 3
else rm -f -- "${'$'}UNIT"; fi
# The complete validated backup remains untouched until restoration and
# service verification succeed, including after an interrupted copy.
rm -rf -- "${'$'}CONFIG"
if [ -f "${'$'}BACKUP/had_config" ]; then
cp -a -- "${'$'}BACKUP/config" "${'$'}CONFIG"
diff -qr -- "${'$'}BACKUP/config" "${'$'}CONFIG" >/dev/null || exit 3
fi
systemctl daemon-reload
if [ -f "${'$'}BACKUP/was_enabled" ]; then
systemctl enable wdtt >/dev/null 2>&1
elif [ -f "${'$'}BACKUP/had_service" ]; then
systemctl disable wdtt >/dev/null 2>&1
fi
if [ -f "${'$'}BACKUP/was_active" ]; then
systemctl restart wdtt
sleep 2
systemctl is-active --quiet wdtt || exit 3
else
! systemctl is-active --quiet wdtt || exit 3
fi
for pair in 'had_binary' 'had_service' 'had_config'; do
case "${'$'}pair" in had_binary) path="${'$'}BINARY" ;; had_service) path="${'$'}UNIT" ;; had_config) path="${'$'}CONFIG" ;; esac
if [ -f "${'$'}BACKUP/${'$'}pair" ]; then
[ -e "${'$'}path" ] && [ ! -L "${'$'}path" ] || exit 3
else [ ! -e "${'$'}path" ] && [ ! -L "${'$'}path" ] || exit 3; fi
done
wdtt_discard_backup
echo WDTT_ROLLBACK=ok
""".trimIndent()
@@ -48,7 +48,7 @@ class NativeVkBrokerService : Service() {
internal object NativeVkBackend {
suspend fun post(raw: String): JSONObject = withContext(Dispatchers.IO) {
val json = JSONObject(raw)
require(json.optString("o") in setOf("prepare", "auth", "permit", "result", "finish"))
require(json.optString("o") in setOf("prepare", "auth", "permit", "result", "finish", "event"))
val encrypted = NativeVkCrypto.exchange(raw)
val bytes = encrypted.request.toByteArray(Charsets.UTF_8)
val url = "https://wdttplus.ru/api/client/native"
@@ -22,10 +22,10 @@ internal object NativeVkProtocol {
fun payload(key: String, device: String, op: String, extras: JSONObject = JSONObject()): String {
require(Regex("[A-Za-z0-9_.-]{24,100}").matches(key))
require(Regex("[A-Za-z0-9_.:-]{8,128}").matches(device))
require(op in setOf("prepare", "auth", "permit", "result", "finish"))
require(op in setOf("prepare", "auth", "permit", "result", "finish", "event"))
val result = JSONObject().put("k", key).put("d", device).put("o", op)
extras.keys().forEach { field ->
require(field in setOf("a", "v", "i", "n"))
require(field in setOf("a", "v", "i", "n", "e"))
result.put(field, extras.get(field))
}
return result.toString().also { require(it.toByteArray(Charsets.UTF_8).size <= 768) }
@@ -22,12 +22,16 @@ import com.wdtt.plus.RemoteLaunchTarget
import com.wdtt.plus.SecureStringStore
import com.wdtt.plus.TemporaryDirectRouteLease
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
@@ -39,6 +43,7 @@ private class ModernVkSafeFallbackException : IllegalStateException("Нужен
/** Device-side provider adapter. Entitlements and result delivery remain server-authoritative. */
@Keep
object VkContinuationExecutor : LocalContinuationExtension {
private val statisticsScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private data class ActiveCallback(val result: CompletableDeferred<Uri?>)
private data class PendingCompletion(
val completion: RemoteActionCompletion,
@@ -104,6 +109,7 @@ object VkContinuationExecutor : LocalContinuationExtension {
}
try {
savePending(activity, PendingCompletion(target.completion, deviceId))
recordStatistics(target, deviceId, "primary_start")
val modernResult = try {
runModernContainer(
activity = activity,
@@ -115,6 +121,7 @@ object VkContinuationExecutor : LocalContinuationExtension {
retainFallbackWindow = { closeModernWindow = it },
)
} catch (_: ModernVkSafeFallbackException) {
recordStatistics(target, deviceId, "primary_fallback")
noteVkEvent("Основной способ недоступен до создания ссылок. Открываю резервный способ внутри приложения.")
progress(onProgress, "Открываю резервный способ внутри приложения…")
null
@@ -124,6 +131,7 @@ object VkContinuationExecutor : LocalContinuationExtension {
callback = replaceCallback(callback)
val native = nativeContinuationOrNull()
if (native != null) {
recordStatistics(target, deviceId, "compatible_start")
try {
return native.execute(
activity,
@@ -133,12 +141,20 @@ object VkContinuationExecutor : LocalContinuationExtension {
onProgress,
).also { markReadyDocument(activity, it) }
} catch (_: LocalContinuationSafeFallbackException) {
recordStatistics(target, deviceId, "compatible_fallback")
noteVkEvent("Встроенный резервный способ не подошёл до создания ссылок. Открываю ВК в браузере.")
progress(onProgress, "Открываю резервный способ в браузере…")
}
}
callback = replaceCallback(callback)
recordStatistics(target, deviceId, "browser_start")
return runBrowserFallback(activity, target, deviceId, onProgress, callback)
} catch (cancelled: CancellationException) {
recordStatistics(target, deviceId, "cancelled")
throw cancelled
} catch (error: Exception) {
recordStatistics(target, deviceId, "failed")
throw error
} finally {
closeModernWindow?.invoke()
synchronized(callbackLock) {
@@ -147,6 +163,24 @@ object VkContinuationExecutor : LocalContinuationExtension {
}
}
private fun recordStatistics(target: RemoteLaunchTarget, deviceId: String, event: String) {
// Observational only: telemetry must never delay VK login, a call permit,
// result delivery, or a safe fallback. The backend authenticates the
// opaque flow and deduplicates this closed set; it owns success counts.
statisticsScope.launch {
runCatching {
NativeVkBackend.post(
NativeVkProtocol.payload(
target.completion.key,
deviceId,
"event",
JSONObject().put("e", event),
),
)
}
}
}
private suspend fun runModernContainer(
activity: MainActivity,
target: RemoteLaunchTarget,
@@ -16,7 +16,7 @@ class DeployDataSafetyTest {
val missing = runRollbackProbe(File(root, "missing"))
assertTrue(missing is ServerUpdateRollbackState.None)
val backup = File(root, "backup").apply { mkdirs() }
val backup = File(root, "backup").apply { mkdirs(); setReadable(false, false); setWritable(false, false); setExecutable(false, false); setReadable(true, true); setWritable(true, true); setExecutable(true, true) }
File(backup, "state").writeText("prepared\n")
File(backup, "had_config").createNewFile()
File(backup, "config").mkdir()
@@ -48,7 +48,7 @@ class DeployDataSafetyTest {
assertTrue("Восстановить прежнее состояние" in source)
assertTrue("server-update-backup-cleanup" in source)
assertTrue("systemctl is-active --quiet wdtt" in source)
assertTrue("WDTT_UPDATE_BACKUP=stale" in source)
assertTrue("WDTT_UPDATE_BACKUP=stale" in prepareServerUpdateRollbackScript())
}
private fun runRollbackProbe(backup: File): ServerUpdateRollbackState {
@@ -136,7 +136,7 @@ class DeployDataSafetyTest {
assertTrue(
"managed Android reset must prepare rollback",
"DeploymentOwnership.IncompleteAndroidDeploy" in source &&
"prepareServerUpdateRollback(ssh)" in source
"prepareServerUpdateRollback(ssh, updateAttemptId)" in source
)
}
@@ -0,0 +1,56 @@
package com.wdtt.plus.ui
import java.io.File
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerUpdateDiagnosticsTest {
private fun snapshot(state: ServerUpdateRollbackState) = ServerUpdateDiagnosticSnapshot(
rollbackState = state,
serviceExists = true,
binaryExists = true,
configDirExists = true,
accessDbExists = true,
wgKeysExist = true,
serviceActive = true,
inspectionSucceeded = true,
)
@Test
fun `report includes only bounded inspection results`() {
val report = buildServerUpdateDiagnosticReport(
snapshot(ServerUpdateRollbackState.PreparedCorrupted("checksum mismatch")),
generatedAt = "2026-09-30T12:00:00Z",
appVersion = "20",
)
assertTrue(report.contains("Состояние страховочной копии: prepared_corrupted"))
assertTrue(report.contains("Код проверки копии: checksum_mismatch"))
assertTrue(report.contains("Служба активна: yes"))
assertTrue(report.contains("База доступа обнаружена: yes"))
}
@Test
fun `unknown remote diagnostic is never copied into report`() {
val secret = "secret-host.example token=not-for-export"
val report = buildServerUpdateDiagnosticReport(
snapshot(ServerUpdateRollbackState.UnknownState(secret)),
generatedAt = "2026-09-30T12:00:00Z",
appVersion = "20",
)
assertTrue(report.contains("Код проверки копии: other"))
assertFalse(report.contains(secret))
assertFalse(report.contains("secret-host.example"))
}
@Test
fun `unsafe rollback dialog exposes only read only extra actions`() {
val source = sequenceOf(
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
).first(File::isFile).readText()
assertTrue(source.contains("Повторить проверку"))
assertTrue(source.contains("Сохранить диагностику"))
assertTrue(source.contains("startDeployCheck(deployRequest, requireExistingServer = true)"))
}
}
@@ -0,0 +1,312 @@
package com.wdtt.plus.ui
import java.io.File
import java.nio.file.Files
import java.util.concurrent.TimeUnit
import org.junit.Assert.*
import org.junit.Test
class ServerUpdateSafetyTest {
private class Host : AutoCloseable {
val root = Files.createTempDirectory("wdtt-update-safety-").toFile()
private val tools = File(root, "tools").apply { mkdir() }
val paths = ServerUpdatePaths(
backup = File(root, "backup").path,
config = File(root, "config").path,
binary = File(root, "server").path,
unit = File(root, "service").path,
lock = File(root, "update.lock").path,
)
val active = File(root, "active")
val events = File(root, "events")
val attempt = "test-attempt"
init {
File(paths.config).mkdir()
File(paths.config, "passwords.json").writeText("{\"main_password\":\"fixture\",\"devices\":{},\"passwords\":{}}")
File(paths.config, "server.log").writeText("old-stats")
File(paths.config, "nested").mkdir()
File(paths.config, "nested/settings with spaces").writeText("kept")
File(paths.binary).apply { writeText("old-server"); setExecutable(true) }
File(paths.unit).writeText("old-unit")
active.writeText("active")
events.writeText("")
executable("systemctl", """
#!/bin/bash
printf '%s\n' "${'$'}1" >> '${events.path}'
case "${'$'}1" in
is-active) [ -f '${active.path}' ] ;;
is-enabled) exit 0 ;;
stop) rm -f '${active.path}'; if [ -d '${paths.config}' ]; then printf 'flushed-stats' > '${paths.config}/server.log'; fi ;;
start|restart) [ "${'$'}{FAIL_START:-0}" = 0 ] || exit 1; touch '${active.path}' ;;
*) exit 0 ;;
esac
""".trimIndent())
executable("cp", """
#!/bin/bash
if [ "${'$'}{FAIL_CP:-0}" = 1 ]; then echo 'copy fixture failed' >&2; exit 65; fi
if [ "${'$'}{HUP_CP:-0}" = 1 ]; then kill -HUP "${'$'}PPID"; exit 66; fi
/bin/cp "${'$'}@" || exit "${'$'}?"
# Models the original race: an active daemon changes its source after copying.
if [ -f '${active.path}' ]; then printf 'changed-by-daemon' > '${paths.config}/server.log'; fi
""".trimIndent())
executable("rm", """
#!/bin/bash
if [ "${'$'}{FAIL_CLEANUP:-0}" = 1 ] && [[ "${'$'}*" = *'.completed.'* ]]; then exit 67; fi
exec /bin/rm "${'$'}@"
""".trimIndent())
executable("df", """
#!/bin/bash
if [ "${'$'}{NO_SPACE:-0}" = 1 ]; then
printf 'Filesystem 1024-blocks Used Available Capacity Mounted\nfixture 100 99 1 99%% /\n'
else exec /bin/df "${'$'}@"; fi
""".trimIndent())
}
private fun executable(name: String, text: String) {
File(tools, name).apply { writeText(text + "\n"); setExecutable(true) }
}
fun run(script: String, vararg env: Pair<String, String>): Pair<Int, String> {
val builder = ProcessBuilder("bash", "-c", script).redirectErrorStream(true)
builder.environment()["PATH"] = tools.path + ":" + System.getenv("PATH")
env.forEach { builder.environment()[it.first] = it.second }
val process = builder.start()
if (!process.waitFor(15, TimeUnit.SECONDS)) {
process.destroyForcibly()
fail("shell test timed out")
}
val output = process.inputStream.bufferedReader().readText()
return process.exitValue() to output
}
fun prepare(vararg env: Pair<String, String>) = run(prepareServerUpdateRollbackScript(paths, attempt), *env)
fun probe() = parseServerUpdateRollbackState(run(serverUpdateRollbackProbeScript(paths.backup)).second)
fun privateBackup() = File(paths.backup).apply {
mkdirs()
Files.setPosixFilePermissions(toPath(), java.nio.file.attribute.PosixFilePermissions.fromString("rwx------"))
}
override fun close() { root.deleteRecursively() }
}
@Test fun `stable preparation stops daemon and includes its last flushed data`() = Host().use { host ->
val result = host.prepare()
assertEquals(result.second, 0, result.first)
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedValid)
assertFalse("daemon must remain quiescent until installation", host.active.exists())
assertEquals("flushed-stats", File(host.paths.backup, "config/server.log").readText())
assertEquals("kept", File(host.paths.backup, "config/nested/settings with spaces").readText())
assertTrue(File(host.paths.backup, "checksums").isFile)
}
@Test fun `copy failure resumes old service and preserves partial copy away from active path`() = Host().use { host ->
val result = host.prepare("FAIL_CP" to "1")
assertNotEquals(0, result.first)
assertTrue(result.second.contains("copy_config"))
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
val archive = host.root.listFiles()!!.single { it.name.startsWith("backup.incomplete.") }
assertEquals("preparation_failed\n", File(archive, "copy/state").readText())
assertEquals("old-server", File(host.paths.binary).readText())
assertEquals(0, host.prepare().first)
}
@Test fun `lost ssh signal resumes service and does not publish partial backup`() = Host().use { host ->
val result = host.prepare("HUP_CP" to "1")
assertNotEquals(0, result.first)
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
assertTrue(host.root.listFiles()!!.any { it.name.startsWith("backup.incomplete.") })
}
@Test fun `restart failure leaves a recoverable preparation rather than deleting evidence`() = Host().use { host ->
val result = host.prepare("FAIL_CP" to "1", "FAIL_START" to "1")
assertNotEquals(0, result.first)
assertEquals(ServerUpdateRollbackState.PreparationIncomplete, host.probe())
assertFalse(host.active.exists())
val recovered = host.run(cancelServerUpdatePreparationScript(host.paths))
assertEquals(recovered.second, 0, recovered.first)
assertTrue(host.active.exists())
assertEquals(ServerUpdateRollbackState.None, host.probe())
}
@Test fun `complete backup corruption and extra files fail checksum validation`() = Host().use { host ->
assertEquals(0, host.prepare().first)
val config = File(host.paths.backup, "config/server.log")
val original = config.readText()
config.writeText("tampered")
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedCorrupted)
config.writeText(original)
File(host.paths.backup, "config/extra").writeText("unexpected")
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedCorrupted)
}
@Test fun `applying and committed phases retain integrity but committed cannot be applied again`() = Host().use { host ->
assertEquals(0, host.prepare().first)
val apply = host.run(serverUpdateApplyGuardScript("echo applied", host.attempt, host.paths))
assertEquals(apply.second, 0, apply.first)
assertEquals("applying\n", File(host.paths.backup, "state").readText())
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedValid)
File(host.paths.backup, "state").writeText("committed\n")
assertEquals(ServerUpdateRollbackState.Committed, host.probe())
assertNotEquals(0, host.run(serverUpdateApplyGuardScript("echo applied", host.attempt, host.paths)).first)
}
@Test fun `another attempt cannot apply or overwrite a prepared backup`() = Host().use { host ->
assertEquals(0, host.prepare().first)
assertNotEquals(0, host.run(serverUpdateApplyGuardScript("echo unsafe", "other", host.paths)).first)
assertNotEquals(0, host.prepare().first)
assertEquals("prepared\n", File(host.paths.backup, "state").readText())
}
@Test fun `unsafe source symlink is rejected without stopping service`() = Host().use { host ->
Files.createSymbolicLink(File(host.paths.config, "foreign").toPath(), File(host.paths.binary).toPath())
assertNotEquals(0, host.prepare().first)
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
assertFalse(host.events.readText().lineSequence().contains("stop"))
}
@Test fun `legacy config only preparation is archived explicitly without changing current files`() = Host().use { host ->
File(host.paths.backup, "config").mkdirs()
host.privateBackup()
File(host.paths.backup, "config/partial").writeText("evidence")
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedCorrupted)
val result = host.run(archiveLegacyUpdatePreparationScript(host.paths))
assertEquals(result.second, 0, result.first)
assertTrue(host.active.exists())
assertEquals("old-server", File(host.paths.binary).readText())
assertEquals(ServerUpdateRollbackState.None, host.probe())
val archive = host.root.listFiles()!!.single { it.name.startsWith("backup.incomplete.") }
assertEquals("evidence", File(archive, "copy/config/partial").readText())
}
@Test fun `unknown legacy state or inactive service cannot be archived`() = Host().use { host ->
File(host.paths.backup, "config").mkdirs()
host.privateBackup()
File(host.paths.backup, "foreign").writeText("unknown")
assertNotEquals(0, host.run(archiveLegacyUpdatePreparationScript(host.paths)).first)
File(host.paths.backup, "foreign").delete()
host.active.delete()
assertNotEquals(0, host.run(archiveLegacyUpdatePreparationScript(host.paths)).first)
assertTrue(File(host.paths.backup).exists())
}
@Test fun `rollback restores the entire verified tree before restarting service`() = Host().use { host ->
assertEquals(0, host.prepare().first)
File(host.paths.binary).writeText("new-server")
File(host.paths.unit).writeText("new-unit")
File(host.paths.config, "nested/settings with spaces").writeText("new-settings")
File(host.paths.config, "added-by-install").writeText("new-file")
host.active.writeText("active")
val result = host.run(rollbackServerUpdateScript(host.paths, host.attempt))
assertEquals(result.second, 0, result.first)
assertTrue(host.active.exists())
assertEquals("old-server", File(host.paths.binary).readText())
assertEquals("old-unit", File(host.paths.unit).readText())
assertEquals("kept", File(host.paths.config, "nested/settings with spaces").readText())
assertFalse(File(host.paths.config, "added-by-install").exists())
assertEquals(ServerUpdateRollbackState.None, host.probe())
}
@Test fun `interrupted rollback remains retryable without losing original backup`() = Host().use { host ->
assertEquals(0, host.prepare().first)
assertNotEquals(0, host.run(rollbackServerUpdateScript(host.paths, host.attempt), "FAIL_CP" to "1").first)
assertFalse(host.active.exists())
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedValid)
val result = host.run(rollbackServerUpdateScript(host.paths, host.attempt))
assertEquals(result.second, 0, result.first)
assertTrue(host.active.exists())
assertEquals("kept", File(host.paths.config, "nested/settings with spaces").readText())
}
@Test fun `corrupt backup cannot stop or overwrite a healthy current installation`() = Host().use { host ->
assertEquals(0, host.prepare().first)
File(host.paths.binary).writeText("new-server")
File(host.paths.backup, "wdtt-server").writeText("corrupt")
host.active.writeText("active")
host.events.writeText("")
assertNotEquals(0, host.run(rollbackServerUpdateScript(host.paths, host.attempt)).first)
assertTrue(host.active.exists())
assertEquals("new-server", File(host.paths.binary).readText())
assertFalse(host.events.readText().lineSequence().contains("stop"))
}
@Test fun `cleanup failure cannot leave a blocking partial backup or revert new installation`() = Host().use { host ->
assertEquals(0, host.prepare().first)
host.active.writeText("active")
File(host.paths.binary).writeText("new-server")
val result = host.run(cleanupServerUpdateBackupScript(host.paths, host.attempt), "FAIL_CLEANUP" to "1")
assertNotEquals(0, result.first)
assertTrue(host.active.exists())
assertEquals("new-server", File(host.paths.binary).readText())
assertEquals(ServerUpdateRollbackState.None, host.probe())
assertTrue(host.root.listFiles()!!.any { it.name.startsWith("backup.completed.") })
}
@Test fun `stopped service remains stopped after preparation failure and rollback`() = Host().use { host ->
host.active.delete()
assertNotEquals(0, host.prepare("FAIL_CP" to "1").first)
assertFalse(host.active.exists())
assertEquals(0, host.prepare().first)
val result = host.run(rollbackServerUpdateScript(host.paths, host.attempt))
assertEquals(result.second, 0, result.first)
assertFalse(host.active.exists())
assertFalse(host.events.readText().lineSequence().contains("restart"))
}
@Test fun `concurrent operation holds lock without stopping daemon or creating backup`() = Host().use { host ->
val blocker = ProcessBuilder("bash", "-c", "exec 9>'${host.paths.lock}'; flock 9; echo ready; read -r ignored")
.redirectErrorStream(true).start()
try {
assertEquals("ready", blocker.inputStream.bufferedReader().readLine())
val result = host.prepare()
assertNotEquals(0, result.first)
assertTrue(result.second.contains("другая операция"))
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
} finally { blocker.outputStream.close(); blocker.waitFor(5, TimeUnit.SECONDS); blocker.destroyForcibly() }
}
@Test fun `missing format or checksums cannot downgrade new backup to legacy validation`() = Host().use { host ->
assertEquals(0, host.prepare().first)
val format = File(host.paths.backup, "format")
format.delete()
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedCorrupted)
format.writeText("2\n")
File(host.paths.backup, "checksums").delete()
assertTrue(host.probe() is ServerUpdateRollbackState.PreparedCorrupted)
}
@Test fun `insufficient snapshot space is rejected before stopping healthy service`() = Host().use { host ->
val result = host.prepare("NO_SPACE" to "1")
assertNotEquals(0, result.first)
assertTrue(result.second.contains("недостаточно свободного места"))
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
assertFalse(host.events.readText().lineSequence().contains("stop"))
}
@Test fun `lock acquisition does not truncate an existing regular lock file`() = Host().use { host ->
File(host.paths.lock).writeText("existing-lock-data")
assertEquals(0, host.prepare().first)
assertEquals("existing-lock-data", File(host.paths.lock).readText())
}
@Test fun `symlink and hardlink lock targets are refused before mutation`() = Host().use { host ->
val target = File(host.root, "foreign-lock-target").apply { writeText("preserve") }
val lock = File(host.paths.lock).toPath()
Files.createSymbolicLink(lock, target.toPath())
assertNotEquals(0, host.prepare().first)
Files.delete(lock)
Files.createLink(lock, target.toPath())
assertNotEquals(0, host.prepare().first)
assertEquals("preserve", target.readText())
assertTrue(host.active.exists())
assertFalse(File(host.paths.backup).exists())
}
@Test fun `failure details remain bounded and redact credentials`() {
val detail = serverUpdateFailureDetail((1..50).joinToString("\n") { "line$it" } + "\nTOKEN=secret-value")
assertFalse(detail.contains("secret-value"))
assertFalse(detail.contains("line1\n"))
assertTrue(detail.contains("line50"))
assertTrue(detail.length <= 3000)
}
}
+13 -11
View File
@@ -4,8 +4,8 @@
из Linux-терминала, без передачи SSH-логина, root-пароля или приватного ключа
Android-приложению.
Комплект для выпуска **WDTT Plus 19** содержит `wdtt-server` версии `19` и
автономный установщик `0.20.2`, совместимый с контрактом Android-деплоя `1`.
Комплект для выпуска **WDTT Plus 20** содержит `wdtt-server` версии `20` и
автономный установщик `0.20.3`, совместимый с контрактом Android-деплоя `1`.
Версии приложения и сервера совпадают; версия скрипта учитывается отдельно,
поскольку он может обновляться без изменения сервера. Используйте файлы из
одного выпуска.
@@ -25,7 +25,7 @@ VK-хеш.
Для установки нужен совместимый комплект:
- `install.sh`;
- исполняемый бинарник `wdtt-server` версии `19` для Linux `amd64`
- исполняемый бинарник `wdtt-server` версии `20` для Linux `amd64`
(`x86_64`);
- `SHA256SUMS` для проверки скрипта и бинарника.
@@ -43,8 +43,8 @@ VK-хеш.
На странице выпуска WDTT Plus в разделе **Assets**, рядом с APK, публикуются:
```text
WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz
WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz.sha256
WDTT-Plus-server-v20-installer-0.20.3-linux-amd64.tar.gz
WDTT-Plus-server-v20-installer-0.20.3-linux-amd64.tar.gz.sha256
```
При канонической предрелизной подготовке эти файлы создаются вместе с четырьмя
@@ -59,9 +59,9 @@ app/build/outputs/release-ready/
архив:
```bash
sha256sum -c WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz.sha256
tar -xzf WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz
cd WDTT-Plus-server-v19-installer-0.20.2-linux-amd64
sha256sum -c WDTT-Plus-server-v20-installer-0.20.3-linux-amd64.tar.gz.sha256
tar -xzf WDTT-Plus-server-v20-installer-0.20.3-linux-amd64.tar.gz
cd WDTT-Plus-server-v20-installer-0.20.3-linux-amd64
```
После распаковки внутри находятся три согласованных файла:
@@ -72,7 +72,7 @@ wdtt-server
SHA256SUMS
```
Это статический Linux `amd64`-файл `wdtt-server` версии `19`; внешние
Это статический Linux `amd64`-файл `wdtt-server` версии `20`; внешние
динамические библиотеки ему не нужны. Проверьте внутренние файлы и их версии:
```bash
@@ -82,7 +82,7 @@ bash install.sh --version
```
Проверка должна сообщить `install.sh: OK`, `wdtt-server: OK`, версию
установщика `0.20.2` и версию сервера `19`.
установщика `0.20.3` и версию сервера `20`.
Готовые бинарник и контрольные суммы публикуются как файлы конкретного
выпуска, но не хранятся в истории Git. Так пользователь получает проверенный
@@ -388,7 +388,7 @@ VPS. Пока сервер принадлежит ручному установ
### Резервные копии после ручной установки
Совместимый `wdtt-server` v19 поддерживает тот же менеджер резервных копий и
Совместимый `wdtt-server` v20 поддерживает тот же менеджер резервных копий и
после установки через этот скрипт. Управление находится в Android-приложении:
**«Деплой» → «Резервные копии и перенос»**. Для административных действий
нужны SSH-доступ к VPS и главный пароль WDTT; обычное VPN-подключение по-прежнему
@@ -860,6 +860,8 @@ SSH нужен только для ручной установки, админи
## Версии ручного установщика
- `0.20.3` — добавлена совместимость с `wdtt-server` v20 и Android-деплоем
выпуска 20; сохранены данные, настройки и согласованный контракт установки.
- `0.20.2` — добавлена совместимость с `wdtt-server` v19 и Android-деплоем
выпуска 19; обновление сохраняет данные, ключи, настройки и резервные копии.
- `0.20.1` — добавлена совместимость с `wdtt-server` v18; обновление сохраняет
+1 -1
View File
@@ -1,7 +1,7 @@
# Canonical compatibility contract for Android deploy and standalone installer.
# Changing any value requires updating both paths; the build guard enforces it.
WDTT_DEPLOY_CONTRACT_VERSION="1"
WDTT_SERVER_VERSION="19"
WDTT_SERVER_VERSION="20"
WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server"
WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service"
WDTT_CONFIG_DIRECTORY="/etc/wdtt"
+2 -2
View File
@@ -23,8 +23,8 @@ ensure_utf8_locale() {
ensure_utf8_locale
readonly INSTALLER_VERSION="0.20.2"
readonly SUPPORTED_SERVER_VERSION="19"
readonly INSTALLER_VERSION="0.20.3"
readonly SUPPORTED_SERVER_VERSION="20"
readonly DEPLOY_COMPATIBILITY_VERSION="1"
readonly MANAGED_MARKER="Managed by WDTT Plus standalone server installer"
readonly ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy"
+8 -8
View File
@@ -38,7 +38,7 @@ new_sandbox() {
make_fake_binary() {
local target="$1"
local build_id="$2"
local reported_version="${3:-19}"
local reported_version="${3:-20}"
cat >"$target" <<EOF
#!/usr/bin/env bash
if [[ "\${1:-}" == "--version" ]]; then
@@ -164,7 +164,7 @@ test_help_and_syntax() {
output="$(mktemp /tmp/wdtt-installer-menu.XXXXXX)"
bash -n "$INSTALLER"
"$INSTALLER" --help >"$output"
[[ "$("$INSTALLER" --version)" == "0.20.2" ]] ||
[[ "$("$INSTALLER" --version)" == "0.20.3" ]] ||
fail "команда --version вернула неожиданный результат"
! grep -Fq "install.sh start" "$output" ||
fail "справка показывает alias start как отдельный основной сценарий"
@@ -383,7 +383,7 @@ test_wizard_on_android_deploy_is_guidance_not_failure() {
tr -d '\r' <"$output" >"$clean"
grep -Fq "На сервере уже обнаружен совместимый Android-деплой." "$clean" ||
fail "мастер не объяснил найденный Android-деплой"
grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 19." "$clean" ||
grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 20." "$clean" ||
fail "мастер не показал краткую совместимость"
grep -Fq "Сейчас изменений на сервере не выполнено." "$clean" ||
fail "мастер не подтвердил отсутствие изменений"
@@ -1829,20 +1829,20 @@ test_installer_version_difference_triggers_update() {
run_installer "$root" install --binary "$binary" --yes >"$output"
grep -Fq "установщик: 0.20.2" "$output" ||
grep -Fq "установщик: 0.20.3" "$output" ||
fail "план не показал версию запущенного установщика"
grep -Fq "установлен: 0.2.0" "$output" ||
fail "план не показал прежнюю установленную версию"
grep -Fxq "installer_version=0.20.2" "$ownership" ||
grep -Fxq "installer_version=0.20.3" "$ownership" ||
fail "повтор не обновил версию в метке владения"
find "$root/var/lib/wdtt-server-installer/backups" -mindepth 1 -maxdepth 1 \
-type d | grep -q . ||
fail "различие версий ошибочно обработано как no-op"
run_installer "$root" status >"$output"
grep -Fq "Версия этого установщика: 0.20.2" "$output" ||
grep -Fq "Версия этого установщика: 0.20.3" "$output" ||
fail "status не показывает версию файла"
grep -Fq "Установлено версией: 0.20.2" "$output" ||
grep -Fq "Установлено версией: 0.20.3" "$output" ||
fail "status не показывает установленную версию"
grep -Fq "Версии установщика: совпадают" "$output" ||
fail "status не сравнивает версии"
@@ -1862,7 +1862,7 @@ test_rejects_incompatible_server_version() {
make_config "$config" "SafeOwnerPassword42"
expect_failure "$output" run_installer "$root" check --binary "$binary" --config "$config"
grep -Fq "Поддерживается wdtt-server версии 19" "$output" ||
grep -Fq "Поддерживается wdtt-server версии 20" "$output" ||
fail "несовместимая версия сервера отклонена без понятной ошибки"
pass "несовместимая версия wdtt-server отклоняется"
}
+1 -1
View File
@@ -50,7 +50,7 @@ import (
)
const (
wdttServerVersion = "19"
wdttServerVersion = "20"
wgIfaceName = "wdtt0"
wgServerAddr = "10.66.66.1"
wgServerCIDR = wgServerAddr + "/24"