diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 76d7216..783fc78 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,6 +16,9 @@ on: permissions: contents: write +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + jobs: build-windows: runs-on: windows-latest @@ -318,8 +321,99 @@ jobs: dist/TgWsProxy_linux_amd64 dist/TgWsProxy_linux_amd64.deb + build-android: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + ANDROID_APK_STANDARD_NAME: tg-ws-proxy-android-${{ github.event.inputs.version }}.apk + ANDROID_APK_LEGACY32_NAME: tg-ws-proxy-android-${{ github.event.inputs.version }}-legacy32.apk + defaults: + run: + working-directory: android + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Validate Android release signing secrets + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + test -n "$ANDROID_KEYSTORE_BASE64" || { echo "Missing secret: ANDROID_KEYSTORE_BASE64"; exit 1; } + test -n "$ANDROID_KEYSTORE_PASSWORD" || { echo "Missing secret: ANDROID_KEYSTORE_PASSWORD"; exit 1; } + test -n "$ANDROID_KEY_ALIAS" || { echo "Missing secret: ANDROID_KEY_ALIAS"; exit 1; } + test -n "$ANDROID_KEY_PASSWORD" || { echo "Missing secret: ANDROID_KEY_PASSWORD"; exit 1; } + + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + cache: gradle + cache-dependency-path: | + android/settings.gradle.kts + android/build.gradle.kts + android/gradle.properties + android/app/build.gradle.kts + + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Set up Android SDK + uses: android-actions/setup-android@v3 + + - name: Accept Android SDK licenses + run: yes | sdkmanager --licenses > /dev/null + + - name: Install Android SDK packages + run: sdkmanager "platforms;android-34" "build-tools;34.0.0" + + - name: Prepare Android release keystore + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + run: | + printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$RUNNER_TEMP/android-release.keystore" + test -s "$RUNNER_TEMP/android-release.keystore" + + - name: Build Android release APKs + env: + LOCAL_CHAQUOPY_REPO: ${{ github.workspace }}/android/.m2-chaquopy-ci + ANDROID_KEYSTORE_FILE: ${{ runner.temp }}/android-release.keystore + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + chmod +x gradlew build-local-debug.sh + ./build-local-debug.sh assembleStandardRelease + ./build-local-debug.sh assembleLegacy32Release + + - name: Rename APKs + run: | + cp app/build/outputs/apk/standard/release/app-standard-release.apk \ + "app/build/outputs/apk/standard/release/$ANDROID_APK_STANDARD_NAME" + cp app/build/outputs/apk/legacy32/release/app-legacy32-release.apk \ + "app/build/outputs/apk/legacy32/release/$ANDROID_APK_LEGACY32_NAME" + + - name: Stage Android release artifacts + run: | + mkdir -p dist + cp "app/build/outputs/apk/standard/release/$ANDROID_APK_STANDARD_NAME" "dist/$ANDROID_APK_STANDARD_NAME" + cp "app/build/outputs/apk/legacy32/release/$ANDROID_APK_LEGACY32_NAME" "dist/$ANDROID_APK_LEGACY32_NAME" + + - name: Upload artifact + uses: actions/upload-artifact@v7 + with: + name: TgWsProxy-android-release + path: | + android/dist/${{ env.ANDROID_APK_STANDARD_NAME }} + android/dist/${{ env.ANDROID_APK_LEGACY32_NAME }} + release: - needs: [build-windows, build-win7, build-macos, build-linux] + needs: [build-windows, build-win7, build-macos, build-linux, build-android] runs-on: ubuntu-latest if: ${{ github.event.inputs.make_release == 'true' }} steps: @@ -329,6 +423,12 @@ jobs: path: dist merge-multiple: true + - name: Download Android build + uses: actions/download-artifact@v8 + with: + name: TgWsProxy-android-release + path: dist + - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: @@ -343,6 +443,8 @@ jobs: dist/TgWsProxy_macos_universal.dmg dist/TgWsProxy_linux_amd64 dist/TgWsProxy_linux_amd64.deb + dist/tg-ws-proxy-android-${{ github.event.inputs.version }}.apk + dist/tg-ws-proxy-android-${{ github.event.inputs.version }}-legacy32.apk draft: false prerelease: false env: diff --git a/.gitignore b/.gitignore index 8aee6ca..8c51ee6 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,18 @@ build/ .idea/ *.swp *.swo +.gradle/ +.gradle-local/ +android/.gradle-local/ +android/.m2-chaquopy*/ +local.properties +android/.idea/ +android/build/ +android/app/build/ +android/app/build +android/*.jks +*.keystore +android/*.keystore.properties # OS Thumbs.db diff --git a/README.md b/README.md index 5c2fd0f..b6f33ff 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,23 @@ chmod +x TgWsProxy_linux_amd64 При первом запуске откроется окно с инструкцией. Приложение работает в системном трее (требуется AppIndicator). +### Android + +Перейдите на [страницу релизов](https://github.com/Flowseal/tg-ws-proxy/releases) и скачайте подписанный APK вида **`tg-ws-proxy-android-vX.Y.Z.apk`**. + +После установки: + +- откройте приложение +- проверьте `Android background limits` +- при необходимости отключите battery optimization и снимите background restrictions +- нажмите **Start Service** +- нажмите **Open in Telegram** + +Что важно для стабильной работы на Android: + +- разрешите уведомления +- отключите battery optimization для приложения + ## Установка из исходников ### Консольный proxy @@ -121,6 +138,20 @@ tg-ws-proxy-tray-linux tg-ws-proxy [--port PORT] [--host HOST] [--dc-ip DC:IP ...] [-v] ``` +### Android debug APK + +Требуются JDK 17, Android SDK и Gradle. Локальная debug-сборка: + +```bash +./android/build-local-debug.sh assembleStandardDebug +``` + +Результат: + +```text +android/app/build/outputs/apk/standard/debug/app-standard-debug.apk +``` + **Аргументы:** | Аргумент | По умолчанию | Описание | @@ -178,6 +209,26 @@ tg-ws-proxy-tray-linux = "linux:main" - **Порт:** `1443` (или переопределенный вами) - **Secret:** из настроек или логов +## Настройка Telegram Android + +### Автоматически + +В приложении нажмите **Open in Telegram** после запуска foreground service. + +### Вручную + +1. Telegram → **Настройки** → **Данные и память** → **Настройки прокси** +2. Добавить прокси: + - **Тип:** MTProto + - **Сервер:** `127.0.0.1` + - **Порт:** `1443` + - **Secret:** из настроек приложения + +Важно: + +- сначала должен быть запущен foreground service +- если Telegram был уже открыт, иногда проще закрыть и открыть его заново после запуска прокси + ## Конфигурация Tray-приложение хранит данные в: @@ -217,7 +268,6 @@ Tray-приложение хранит данные в: - Intel macOS 10.15+ - Apple Silicon macOS 11.0+ - Linux x86_64 (требуется AppIndicator для системного трея) - ## Лицензия [MIT License](LICENSE) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..bf3d97d --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,170 @@ +import org.gradle.api.tasks.Sync +import org.gradle.api.GradleException +import java.io.File + +plugins { + id("com.android.application") + id("com.chaquo.python") + id("org.jetbrains.kotlin.android") +} + +fun loadProxyVersionName(): String { + val versionFile = rootProject.projectDir.resolve("../proxy/__init__.py") + val match = Regex("""__version__\s*=\s*"([^"]+)"""") + .find(versionFile.readText()) + ?: throw GradleException("Failed to parse proxy version from ${versionFile.absolutePath}") + return match.groupValues[1] +} + +data class ReleaseSigningEnv( + val keystoreFile: File, + val storePassword: String, + val keyAlias: String, + val keyPassword: String, +) + +fun requiredEnv(name: String): String { + return System.getenv(name)?.takeIf { it.isNotBlank() } + ?: throw GradleException("Missing required environment variable: $name") +} + +fun loadReleaseSigningEnv(releaseSigningRequested: Boolean): ReleaseSigningEnv? { + val keystorePath = System.getenv("ANDROID_KEYSTORE_FILE")?.takeIf { it.isNotBlank() } + val anySigningEnvProvided = listOf( + keystorePath, + System.getenv("ANDROID_KEYSTORE_PASSWORD"), + System.getenv("ANDROID_KEY_ALIAS"), + System.getenv("ANDROID_KEY_PASSWORD"), + ).any { !it.isNullOrBlank() } + + if (!releaseSigningRequested && !anySigningEnvProvided) { + return null + } + + val keystoreFile = File(requiredEnv("ANDROID_KEYSTORE_FILE")) + if (!keystoreFile.isFile) { + throw GradleException("ANDROID_KEYSTORE_FILE does not exist: ${keystoreFile.absolutePath}") + } + + return ReleaseSigningEnv( + keystoreFile = keystoreFile, + storePassword = requiredEnv("ANDROID_KEYSTORE_PASSWORD"), + keyAlias = requiredEnv("ANDROID_KEY_ALIAS"), + keyPassword = requiredEnv("ANDROID_KEY_PASSWORD"), + ) +} + +val stagedPythonSourcesDir = layout.buildDirectory.dir("generated/chaquopy/python") +val stagePythonSources by tasks.registering(Sync::class) { + from(rootProject.projectDir.resolve("../proxy")) { + into("proxy") + } + from(rootProject.projectDir.resolve("../utils")) { + into("utils") + } + into(stagedPythonSourcesDir) +} +val releaseSigningRequested = gradle.startParameter.taskNames.any { + it.contains("release", ignoreCase = true) +} +val releaseSigningEnv = loadReleaseSigningEnv(releaseSigningRequested) +val appVersionName = loadProxyVersionName() + +android { + namespace = "org.flowseal.tgwsproxy" + compileSdk = 34 + + defaultConfig { + applicationId = "org.flowseal.tgwsproxy" + minSdk = 26 + targetSdk = 34 + versionCode = 1 + versionName = appVersionName + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + flavorDimensions += "runtime" + productFlavors { + create("standard") { + dimension = "runtime" + ndk { + abiFilters += listOf("arm64-v8a", "x86_64") + } + } + create("legacy32") { + dimension = "runtime" + versionNameSuffix = "-legacy32" + ndk { + abiFilters += listOf("armeabi-v7a") + } + } + } + + signingConfigs { + if (releaseSigningEnv != null) { + create("release") { + storeFile = releaseSigningEnv.keystoreFile + storePassword = releaseSigningEnv.storePassword + keyAlias = releaseSigningEnv.keyAlias + keyPassword = releaseSigningEnv.keyPassword + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) + if (releaseSigningEnv != null) { + signingConfig = signingConfigs.getByName("release") + } + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + buildFeatures { + viewBinding = true + } +} + +chaquopy { + productFlavors { + getByName("standard") { + version = "3.12" + } + getByName("legacy32") { + version = "3.11" + } + } + sourceSets { + getByName("main") { + srcDir("src/main/python") + srcDir(stagePythonSources) + } + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.13.1") + implementation("androidx.appcompat:appcompat:1.7.0") + implementation("androidx.activity:activity-ktx:1.9.2") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6") + implementation("androidx.lifecycle:lifecycle-service:2.8.6") + implementation("com.google.android.material:material:1.12.0") + + testImplementation("junit:junit:4.13.2") + androidTestImplementation("androidx.test.ext:junit:1.2.1") + androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1") +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..dc67027 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1 @@ +# Intentionally empty for the initial Android shell. diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4f8e290 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/AndroidSystemStatus.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/AndroidSystemStatus.kt new file mode 100644 index 0000000..47bfa75 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/AndroidSystemStatus.kt @@ -0,0 +1,62 @@ +package org.flowseal.tgwsproxy + +import android.app.ActivityManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.PowerManager +import android.provider.Settings + +data class AndroidSystemStatus( + val ignoringBatteryOptimizations: Boolean, + val backgroundRestricted: Boolean, +) { + val canKeepRunningReliably: Boolean + get() = ignoringBatteryOptimizations && !backgroundRestricted + + companion object { + fun read(context: Context): AndroidSystemStatus { + val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager + val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + + val ignoringBatteryOptimizations = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + powerManager.isIgnoringBatteryOptimizations(context.packageName) + } else { + true + } + + val backgroundRestricted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + activityManager.isBackgroundRestricted + } else { + false + } + + return AndroidSystemStatus( + ignoringBatteryOptimizations = ignoringBatteryOptimizations, + backgroundRestricted = backgroundRestricted, + ) + } + + fun openBatteryOptimizationSettings(context: Context) { + val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply { + data = Uri.parse("package:${context.packageName}") + } + } else { + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = Uri.fromParts("package", context.packageName, null) + } + } + + context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + fun openAppSettings(context: Context) { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = Uri.fromParts("package", context.packageName, null) + } + context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + } +} diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/LogViewerActivity.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/LogViewerActivity.kt new file mode 100644 index 0000000..63af385 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/LogViewerActivity.kt @@ -0,0 +1,53 @@ +package org.flowseal.tgwsproxy + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import org.flowseal.tgwsproxy.databinding.ActivityLogViewerBinding +import java.io.File + +class LogViewerActivity : AppCompatActivity() { + private lateinit var binding: ActivityLogViewerBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityLogViewerBinding.inflate(layoutInflater) + setContentView(binding.root) + + binding.refreshLogsButton.setOnClickListener { renderLog() } + binding.closeLogsButton.setOnClickListener { finish() } + + renderLog() + } + + override fun onResume() { + super.onResume() + renderLog() + } + + private fun renderLog() { + val logFile = File(filesDir, "tg-ws-proxy/proxy.log") + binding.logPathValue.text = logFile.absolutePath + binding.logContentValue.text = readLogTail(logFile) + } + + private fun readLogTail(logFile: File, maxChars: Int = 40000): String { + if (!logFile.isFile) { + return getString(R.string.logs_empty) + } + + val text = runCatching { + logFile.readText(Charsets.UTF_8) + }.getOrElse { error -> + return getString(R.string.logs_read_failed, error.message ?: error.javaClass.simpleName) + } + + if (text.isBlank()) { + return getString(R.string.logs_empty) + } + if (text.length <= maxChars) { + return text + } + + return getString(R.string.logs_truncated_prefix) + "\n\n" + text.takeLast(maxChars) + } +} diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/MainActivity.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/MainActivity.kt new file mode 100644 index 0000000..28a50f1 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/MainActivity.kt @@ -0,0 +1,330 @@ +package org.flowseal.tgwsproxy + +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.isVisible +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import com.google.android.material.snackbar.Snackbar +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.flowseal.tgwsproxy.databinding.ActivityMainBinding + +class MainActivity : AppCompatActivity() { + private lateinit var binding: ActivityMainBinding + private lateinit var settingsStore: ProxySettingsStore + private var currentUpdateStatus: ProxyUpdateStatus? = null + + private val notificationPermissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { granted -> + if (!granted) { + Toast.makeText( + this, + "Без уведомлений Android может скрыть foreground service.", + Toast.LENGTH_LONG, + ).show() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + settingsStore = ProxySettingsStore(this) + setContentView(binding.root) + + binding.startButton.setOnClickListener { onStartClicked() } + binding.stopButton.setOnClickListener { ProxyForegroundService.stop(this) } + binding.restartButton.setOnClickListener { onRestartClicked() } + binding.saveButton.setOnClickListener { onSaveClicked(showMessage = true) } + binding.openLogsButton.setOnClickListener { onOpenLogsClicked() } + binding.openTelegramButton.setOnClickListener { onOpenTelegramClicked() } + binding.openReleasePageButton.setOnClickListener { onOpenReleasePageClicked() } + binding.checkUpdatesSwitch.setOnCheckedChangeListener { _, _ -> + renderUpdateStatus(currentUpdateStatus, binding.checkUpdatesSwitch.isChecked) + } + binding.disableBatteryOptimizationButton.setOnClickListener { + AndroidSystemStatus.openBatteryOptimizationSettings(this) + } + binding.openAppSettingsButton.setOnClickListener { + AndroidSystemStatus.openAppSettings(this) + } + + val config = settingsStore.load() + renderConfig(config) + if (config.checkUpdates) { + refreshUpdateStatus(checkNow = true) + } else { + currentUpdateStatus = null + renderUpdateStatus(null, false) + } + requestNotificationPermissionIfNeeded() + observeServiceState() + renderSystemStatus() + } + + override fun onResume() { + super.onResume() + renderSystemStatus() + } + + private fun onSaveClicked(showMessage: Boolean): NormalizedProxyConfig? { + val validation = collectConfigFromForm().validate() + val config = validation.normalized + if (config == null) { + binding.errorText.text = validation.errorMessage + binding.errorText.isVisible = true + return null + } + + binding.errorText.isVisible = false + settingsStore.save(config) + if (showMessage) { + Snackbar.make(binding.root, R.string.settings_saved, Snackbar.LENGTH_SHORT).show() + } + if (config.checkUpdates) { + refreshUpdateStatus(checkNow = true) + } else { + currentUpdateStatus = null + renderUpdateStatus(null, false) + } + return config + } + + private fun onStartClicked() { + onSaveClicked(showMessage = false) ?: return + ProxyForegroundService.start(this) + Snackbar.make(binding.root, R.string.service_start_requested, Snackbar.LENGTH_SHORT).show() + } + + private fun onRestartClicked() { + onSaveClicked(showMessage = false) ?: return + ProxyForegroundService.restart(this) + Snackbar.make(binding.root, R.string.service_restart_requested, Snackbar.LENGTH_SHORT).show() + } + + private fun onOpenLogsClicked() { + startActivity(Intent(this, LogViewerActivity::class.java)) + } + + private fun onOpenTelegramClicked() { + val config = onSaveClicked(showMessage = false) ?: return + if (!TelegramProxyIntent.open(this, config)) { + Snackbar.make(binding.root, R.string.telegram_not_found, Snackbar.LENGTH_LONG).show() + } + } + + private fun renderConfig(config: ProxyConfig) { + binding.hostInput.setText(config.host) + binding.portInput.setText(config.portText) + binding.secretInput.setText(config.secretText) + binding.dcIpInput.setText(config.dcIpText) + binding.logMaxMbInput.setText(config.logMaxMbText) + binding.bufferKbInput.setText(config.bufferKbText) + binding.poolSizeInput.setText(config.poolSizeText) + binding.checkUpdatesSwitch.isChecked = config.checkUpdates + binding.verboseSwitch.isChecked = config.verbose + renderUpdateStatus(currentUpdateStatus, config.checkUpdates) + } + + private fun collectConfigFromForm(): ProxyConfig { + return ProxyConfig( + host = binding.hostInput.text?.toString().orEmpty(), + portText = binding.portInput.text?.toString().orEmpty(), + secretText = binding.secretInput.text?.toString().orEmpty(), + dcIpText = binding.dcIpInput.text?.toString().orEmpty(), + logMaxMbText = binding.logMaxMbInput.text?.toString().orEmpty(), + bufferKbText = binding.bufferKbInput.text?.toString().orEmpty(), + poolSizeText = binding.poolSizeInput.text?.toString().orEmpty(), + checkUpdates = binding.checkUpdatesSwitch.isChecked, + verbose = binding.verboseSwitch.isChecked, + ) + } + + private fun onOpenReleasePageClicked() { + val url = currentUpdateStatus?.htmlUrl ?: "https://github.com/Flowseal/tg-ws-proxy/releases/latest" + val opened = runCatching { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + }.isSuccess + if (!opened) { + Snackbar.make(binding.root, R.string.release_page_open_failed, Snackbar.LENGTH_LONG).show() + } + } + + private fun refreshUpdateStatus(checkNow: Boolean) { + lifecycleScope.launch { + val status = runCatching { + withContext(Dispatchers.IO) { + PythonProxyBridge.getUpdateStatus(this@MainActivity, checkNow) + } + }.getOrElse { exc -> + ProxyUpdateStatus( + currentVersion = currentAppVersionName(), + error = exc.message ?: exc.javaClass.simpleName, + ) + } + currentUpdateStatus = status + renderUpdateStatus(status, binding.checkUpdatesSwitch.isChecked) + } + } + + private fun renderUpdateStatus(status: ProxyUpdateStatus?, checkUpdatesEnabled: Boolean) { + val currentVersion = status?.currentVersion?.takeIf { it.isNotBlank() } ?: currentAppVersionName() + binding.currentVersionValue.text = getString( + R.string.updates_current_version_format, + currentVersion, + ) + binding.updateStatusValue.text = when { + !checkUpdatesEnabled -> { + getString(R.string.updates_status_disabled) + } + status == null -> { + getString(R.string.updates_status_initial) + } + !status.error.isNullOrBlank() -> { + getString(R.string.updates_status_error, status.error) + } + !status.checked -> { + getString(R.string.updates_status_idle) + } + status.hasUpdate && !status.latestVersion.isNullOrBlank() -> { + getString( + R.string.updates_status_available, + status.latestVersion, + status.currentVersion, + ) + } + status.aheadOfRelease -> { + getString(R.string.updates_status_newer, status.currentVersion) + } + else -> { + getString(R.string.updates_status_latest, status.currentVersion) + } + } + } + + private fun currentAppVersionName(): String { + return runCatching { + @Suppress("DEPRECATION") + packageManager.getPackageInfo(packageName, 0).versionName + }.getOrNull().orEmpty().ifBlank { "unknown" } + } + + private fun observeServiceState() { + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + combine( + ProxyServiceState.isStarting, + ProxyServiceState.isRunning, + ) { isStarting, isRunning -> + isStarting to isRunning + }.collect { (isStarting, isRunning) -> + binding.statusValue.text = getString( + when { + isStarting -> R.string.status_starting + isRunning -> R.string.status_running + else -> R.string.status_stopped + }, + ) + binding.startButton.isEnabled = !isStarting && !isRunning + binding.stopButton.isEnabled = isStarting || isRunning + binding.restartButton.isEnabled = !isStarting + } + } + } + + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + combine( + ProxyServiceState.activeConfig, + ProxyServiceState.isStarting, + ) { config, isStarting -> + config to isStarting + }.collect { (config, isStarting) -> + binding.serviceHint.text = if (config == null) { + getString(R.string.service_hint_idle) + } else if (isStarting) { + getString( + R.string.service_hint_starting, + config.host, + config.port, + ) + } else { + getString( + R.string.service_hint_running, + config.host, + config.port, + ) + } + } + } + } + + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + ProxyServiceState.lastError.collect { error -> + if (error.isNullOrBlank()) { + binding.lastErrorCard.isVisible = false + } else { + binding.lastErrorValue.text = error + binding.lastErrorCard.isVisible = true + } + } + } + } + } + + private fun renderSystemStatus() { + val status = AndroidSystemStatus.read(this) + + binding.systemStatusValue.text = getString( + if (status.canKeepRunningReliably) { + R.string.system_status_ready + } else { + R.string.system_status_attention + }, + ) + + val lines = mutableListOf() + lines += if (status.ignoringBatteryOptimizations) { + getString(R.string.system_check_battery_ignored) + } else { + getString(R.string.system_check_battery_active) + } + lines += if (status.backgroundRestricted) { + getString(R.string.system_check_background_restricted) + } else { + getString(R.string.system_check_background_ok) + } + lines += getString(R.string.system_check_oem_note) + binding.systemStatusHint.text = lines.joinToString("\n") + + binding.disableBatteryOptimizationButton.isVisible = !status.ignoringBatteryOptimizations + binding.openAppSettingsButton.isVisible = status.backgroundRestricted || !status.ignoringBatteryOptimizations + } + + private fun requestNotificationPermissionIfNeeded() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + return + } + if (ContextCompat.checkSelfPermission( + this, + Manifest.permission.POST_NOTIFICATIONS, + ) == PackageManager.PERMISSION_GRANTED + ) { + return + } + notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + } +} diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyConfig.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyConfig.kt new file mode 100644 index 0000000..89628ea --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyConfig.kt @@ -0,0 +1,156 @@ +package org.flowseal.tgwsproxy + +import java.security.SecureRandom + +data class ProxyConfig( + val host: String = DEFAULT_HOST, + val portText: String = DEFAULT_PORT.toString(), + val secretText: String = DEFAULT_SECRET, + val dcIpText: String = DEFAULT_DC_IP_LINES.joinToString("\n"), + val logMaxMbText: String = formatDecimal(DEFAULT_LOG_MAX_MB), + val bufferKbText: String = DEFAULT_BUFFER_KB.toString(), + val poolSizeText: String = DEFAULT_POOL_SIZE.toString(), + val checkUpdates: Boolean = false, + val verbose: Boolean = false, +) { + fun validate(): ValidationResult { + val hostValue = host.trim() + if (!isIpv4Address(hostValue)) { + return ValidationResult(errorMessage = "IP-адрес прокси указан некорректно.") + } + + val portValue = portText.trim().toIntOrNull() + ?: return ValidationResult(errorMessage = "Порт должен быть числом.") + if (portValue !in 1..65535) { + return ValidationResult(errorMessage = "Порт должен быть в диапазоне 1-65535.") + } + + val secretValue = secretText.trim().lowercase() + if (secretValue.length != 32 || !secretValue.all { it in "0123456789abcdef" }) { + return ValidationResult( + errorMessage = "MTProto secret должен содержать ровно 32 hex-символа." + ) + } + + val lines = dcIpText + .lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .toList() + + if (lines.isEmpty()) { + return ValidationResult(errorMessage = "Добавьте хотя бы один DC:IP маппинг.") + } + + for (line in lines) { + val parts = line.split(":", limit = 2) + val dcValue = parts.firstOrNull()?.toIntOrNull() + val ipValue = parts.getOrNull(1)?.trim().orEmpty() + if (parts.size != 2 || dcValue == null || !isIpv4Address(ipValue)) { + return ValidationResult(errorMessage = "Строка \"$line\" должна быть в формате DC:IP.") + } + } + + val logMaxMbValue = logMaxMbText.trim().toDoubleOrNull() + ?: return ValidationResult( + errorMessage = "Размер лог-файла должен быть числом." + ) + if (logMaxMbValue <= 0.0) { + return ValidationResult( + errorMessage = "Размер лог-файла должен быть больше нуля." + ) + } + + val bufferKbValue = bufferKbText.trim().toIntOrNull() + ?: return ValidationResult( + errorMessage = "Буфер сокета должен быть целым числом." + ) + if (bufferKbValue < 4) { + return ValidationResult( + errorMessage = "Буфер сокета должен быть не меньше 4 KB." + ) + } + + val poolSizeValue = poolSizeText.trim().toIntOrNull() + ?: return ValidationResult( + errorMessage = "Размер WS pool должен быть целым числом." + ) + if (poolSizeValue < 0) { + return ValidationResult( + errorMessage = "Размер WS pool не может быть отрицательным." + ) + } + + return ValidationResult( + normalized = NormalizedProxyConfig( + host = hostValue, + port = portValue, + secret = secretValue, + dcIpList = lines, + logMaxMb = logMaxMbValue, + bufferKb = bufferKbValue, + poolSize = poolSizeValue, + checkUpdates = checkUpdates, + verbose = verbose, + ) + ) + } + + companion object { + const val DEFAULT_HOST = "127.0.0.1" + const val DEFAULT_PORT = 1443 + const val DEFAULT_LOG_MAX_MB = 5.0 + const val DEFAULT_BUFFER_KB = 256 + const val DEFAULT_POOL_SIZE = 4 + val DEFAULT_SECRET = generateSecret() + val DEFAULT_DC_IP_LINES = listOf( + "2:149.154.167.220", + "4:149.154.167.220", + ) + + fun formatDecimal(value: Double): String { + return if (value % 1.0 == 0.0) { + value.toInt().toString() + } else { + value.toString() + } + } + + private fun generateSecret(): String { + val bytes = ByteArray(16) + SecureRandom().nextBytes(bytes) + return bytes.joinToString(separator = "") { "%02x".format(it) } + } + + private fun isIpv4Address(value: String): Boolean { + val octets = value.split(".") + if (octets.size != 4) { + return false + } + + return octets.all { octet -> + octet.isNotEmpty() && + octet.length <= 3 && + octet.all(Char::isDigit) && + octet.toIntOrNull() in 0..255 + } + } + } +} + +data class ValidationResult( + val normalized: NormalizedProxyConfig? = null, + val errorMessage: String? = null, +) + +data class NormalizedProxyConfig( + val host: String, + val port: Int, + val secret: String, + val dcIpList: List, + val logMaxMb: Double, + val bufferKb: Int, + val poolSize: Int, + val checkUpdates: Boolean, + val verbose: Boolean, +) diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyForegroundService.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyForegroundService.kt new file mode 100644 index 0000000..96d5f50 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyForegroundService.kt @@ -0,0 +1,395 @@ +package org.flowseal.tgwsproxy + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.IBinder +import androidx.core.app.TaskStackBuilder +import androidx.core.app.NotificationCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import java.util.Locale + +class ProxyForegroundService : Service() { + private lateinit var settingsStore: ProxySettingsStore + private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private var trafficJob: Job? = null + private var lastTrafficSample: TrafficSample? = null + + override fun onCreate() { + super.onCreate() + settingsStore = ProxySettingsStore(this) + createNotificationChannel() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + return when (intent?.action) { + ACTION_STOP -> { + ProxyServiceState.clearError() + serviceScope.launch { + stopProxyRuntime(removeNotification = true, stopService = true) + } + START_NOT_STICKY + } + + ACTION_RESTART -> { + val config = loadValidatedConfig() ?: return START_NOT_STICKY + ProxyServiceState.clearError() + beginProxyStart(config) + serviceScope.launch { + stopRuntimeOnly() + startProxyRuntime(config) + } + START_STICKY + } + + else -> { + val config = loadValidatedConfig() ?: return START_NOT_STICKY + beginProxyStart(config) + serviceScope.launch { + startProxyRuntime(config) + } + START_STICKY + } + } + } + + override fun onDestroy() { + stopTrafficUpdates() + serviceScope.cancel() + runCatching { PythonProxyBridge.stop(this) } + ProxyServiceState.markStopped() + super.onDestroy() + } + + override fun onBind(intent: Intent?): IBinder? = null + + private fun buildNotification(payload: NotificationPayload): Notification { + return NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.notification_title)) + .setContentText(payload.statusText) + .setSubText(payload.endpointText) + .setStyle( + NotificationCompat.BigTextStyle().bigText(payload.detailsText), + ) + .setSmallIcon(R.drawable.ic_proxy_notification) + .setContentIntent(createOpenAppPendingIntent()) + .addAction( + 0, + getString(R.string.notification_action_stop), + createStopPendingIntent(), + ) + .setOngoing(true) + .setOnlyAlertOnce(true) + .build() + } + + private suspend fun startProxyRuntime(config: NormalizedProxyConfig) { + val result = runCatching { + PythonProxyBridge.start(this, config) + } + + result.onSuccess { + ProxyServiceState.markStarted(config) + lastTrafficSample = null + updateNotification( + buildNotificationPayload( + config = config, + trafficState = TrafficState(running = true), + statusText = getString( + R.string.notification_running, + config.host, + config.port, + ), + ), + ) + startTrafficUpdates(config) + }.onFailure { error -> + ProxyServiceState.markFailed( + error.message ?: getString(R.string.proxy_start_failed_generic), + ) + stopTrafficUpdates() + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + } + + private fun loadValidatedConfig(): NormalizedProxyConfig? { + val config = settingsStore.load().validate().normalized + if (config == null) { + ProxyServiceState.markFailed(getString(R.string.saved_config_invalid)) + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + return config + } + + private fun beginProxyStart(config: NormalizedProxyConfig) { + ProxyServiceState.markStarting(config) + startForeground( + NOTIFICATION_ID, + buildNotification( + buildNotificationPayload( + config = config, + trafficState = TrafficState(), + statusText = getString( + R.string.notification_starting, + config.host, + config.port, + ), + ), + ), + ) + } + + private fun stopProxyRuntime(removeNotification: Boolean, stopService: Boolean) { + stopRuntimeOnly() + ProxyServiceState.markStopped() + + if (removeNotification) { + stopForeground(STOP_FOREGROUND_REMOVE) + } + if (stopService) { + stopSelf() + } + } + + private fun stopRuntimeOnly() { + stopTrafficUpdates() + runCatching { PythonProxyBridge.stop(this) } + } + + private fun updateNotification(payload: NotificationPayload) { + val manager = getSystemService(NotificationManager::class.java) + manager.notify(NOTIFICATION_ID, buildNotification(payload)) + } + + private fun buildNotificationPayload( + config: NormalizedProxyConfig, + trafficState: TrafficState, + statusText: String, + ): NotificationPayload { + val endpointText = getString(R.string.notification_endpoint, config.host, config.port) + val detailsText = getString( + R.string.notification_details, + config.dcIpList.size, + formatRate(trafficState.upBytesPerSecond), + formatRate(trafficState.downBytesPerSecond), + formatBytes(trafficState.totalBytesUp), + formatBytes(trafficState.totalBytesDown), + ) + return NotificationPayload( + statusText = statusText, + endpointText = endpointText, + detailsText = detailsText, + ) + } + + private fun startTrafficUpdates(config: NormalizedProxyConfig) { + stopTrafficUpdates() + trafficJob = serviceScope.launch { + while (isActive && ProxyServiceState.isRunning.value) { + val trafficState = readTrafficState() + if (!trafficState.running) { + ProxyServiceState.markFailed( + trafficState.lastError ?: getString(R.string.proxy_runtime_stopped_unexpectedly), + ) + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + break + } + updateNotification( + buildNotificationPayload( + config = config, + trafficState = trafficState, + statusText = getString( + R.string.notification_running, + config.host, + config.port, + ), + ), + ) + delay(1000) + } + } + } + + private fun stopTrafficUpdates() { + trafficJob?.cancel() + trafficJob = null + lastTrafficSample = null + } + + private fun readTrafficState(): TrafficState { + val nowMillis = System.currentTimeMillis() + val current = PythonProxyBridge.getTrafficStats(this) + val previous = lastTrafficSample + lastTrafficSample = TrafficSample( + bytesUp = current.bytesUp, + bytesDown = current.bytesDown, + timestampMillis = nowMillis, + ) + + if (!current.running || previous == null) { + return TrafficState( + upBytesPerSecond = 0L, + downBytesPerSecond = 0L, + totalBytesUp = current.bytesUp, + totalBytesDown = current.bytesDown, + running = current.running, + lastError = current.lastError, + ) + } + + val elapsedMillis = (nowMillis - previous.timestampMillis).coerceAtLeast(1L) + val upDelta = (current.bytesUp - previous.bytesUp).coerceAtLeast(0L) + val downDelta = (current.bytesDown - previous.bytesDown).coerceAtLeast(0L) + return TrafficState( + upBytesPerSecond = (upDelta * 1000L) / elapsedMillis, + downBytesPerSecond = (downDelta * 1000L) / elapsedMillis, + totalBytesUp = current.bytesUp, + totalBytesDown = current.bytesDown, + running = current.running, + lastError = current.lastError, + ) + } + + private fun formatRate(bytesPerSecond: Long): String = formatBytes(bytesPerSecond) + + private fun formatBytes(bytes: Long): String { + val units = arrayOf("B", "KB", "MB", "GB") + var value = bytes.toDouble().coerceAtLeast(0.0) + var unitIndex = 0 + + while (value >= 1024.0 && unitIndex < units.lastIndex) { + value /= 1024.0 + unitIndex += 1 + } + + return if (unitIndex == 0) { + String.format(Locale.US, "%.0f %s", value, units[unitIndex]) + } else { + String.format(Locale.US, "%.1f %s", value, units[unitIndex]) + } + } + + private fun createOpenAppPendingIntent(): PendingIntent { + val launchIntent = packageManager.getLaunchIntentForPackage(packageName) + ?.apply { + addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_CLEAR_TOP or + Intent.FLAG_ACTIVITY_SINGLE_TOP, + ) + } + ?: Intent(this, MainActivity::class.java).apply { + addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_CLEAR_TOP or + Intent.FLAG_ACTIVITY_SINGLE_TOP, + ) + } + + return TaskStackBuilder.create(this) + .addNextIntentWithParentStack(launchIntent) + .getPendingIntent( + 1, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + ?: PendingIntent.getActivity( + this, + 1, + launchIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun createStopPendingIntent(): PendingIntent { + val intent = Intent(this, ProxyForegroundService::class.java).apply { + action = ACTION_STOP + } + return PendingIntent.getService( + this, + 2, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun createNotificationChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return + } + + val manager = getSystemService(NotificationManager::class.java) + val channel = NotificationChannel( + CHANNEL_ID, + getString(R.string.notification_channel_name), + NotificationManager.IMPORTANCE_LOW, + ).apply { + description = getString(R.string.notification_channel_description) + } + manager.createNotificationChannel(channel) + } + + companion object { + private const val CHANNEL_ID = "proxy_service" + private const val NOTIFICATION_ID = 1001 + private const val ACTION_START = "org.flowseal.tgwsproxy.action.START" + private const val ACTION_STOP = "org.flowseal.tgwsproxy.action.STOP" + private const val ACTION_RESTART = "org.flowseal.tgwsproxy.action.RESTART" + + fun start(context: Context) { + val intent = Intent(context, ProxyForegroundService::class.java).apply { + action = ACTION_START + } + androidx.core.content.ContextCompat.startForegroundService(context, intent) + } + + fun stop(context: Context) { + val intent = Intent(context, ProxyForegroundService::class.java).apply { + action = ACTION_STOP + } + context.startService(intent) + } + + fun restart(context: Context) { + val intent = Intent(context, ProxyForegroundService::class.java).apply { + action = ACTION_RESTART + } + androidx.core.content.ContextCompat.startForegroundService(context, intent) + } + } +} + +private data class NotificationPayload( + val statusText: String, + val endpointText: String, + val detailsText: String, +) + +private data class TrafficSample( + val bytesUp: Long, + val bytesDown: Long, + val timestampMillis: Long, +) + +private data class TrafficState( + val upBytesPerSecond: Long = 0L, + val downBytesPerSecond: Long = 0L, + val totalBytesUp: Long = 0L, + val totalBytesDown: Long = 0L, + val running: Boolean = false, + val lastError: String? = null, +) diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyServiceState.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyServiceState.kt new file mode 100644 index 0000000..ff08fc3 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxyServiceState.kt @@ -0,0 +1,49 @@ +package org.flowseal.tgwsproxy + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +object ProxyServiceState { + private val _isRunning = MutableStateFlow(false) + val isRunning: StateFlow = _isRunning + + private val _isStarting = MutableStateFlow(false) + val isStarting: StateFlow = _isStarting + + private val _activeConfig = MutableStateFlow(null) + val activeConfig: StateFlow = _activeConfig + + private val _lastError = MutableStateFlow(null) + val lastError: StateFlow = _lastError + + fun markStarting(config: NormalizedProxyConfig) { + _activeConfig.value = config + _isStarting.value = true + _isRunning.value = false + _lastError.value = null + } + + fun markStarted(config: NormalizedProxyConfig) { + _activeConfig.value = config + _isStarting.value = false + _isRunning.value = true + _lastError.value = null + } + + fun markFailed(message: String) { + _activeConfig.value = null + _isStarting.value = false + _isRunning.value = false + _lastError.value = message + } + + fun markStopped() { + _activeConfig.value = null + _isStarting.value = false + _isRunning.value = false + } + + fun clearError() { + _lastError.value = null + } +} diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/ProxySettingsStore.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxySettingsStore.kt new file mode 100644 index 0000000..70e51ac --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/ProxySettingsStore.kt @@ -0,0 +1,62 @@ +package org.flowseal.tgwsproxy + +import android.content.Context + +class ProxySettingsStore(context: Context) { + private val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + + fun load(): ProxyConfig { + return ProxyConfig( + host = preferences.getString(KEY_HOST, ProxyConfig.DEFAULT_HOST).orEmpty(), + portText = preferences.getInt(KEY_PORT, ProxyConfig.DEFAULT_PORT).toString(), + secretText = preferences.getString(KEY_SECRET, ProxyConfig.DEFAULT_SECRET).orEmpty(), + dcIpText = preferences.getString( + KEY_DC_IP_TEXT, + ProxyConfig.DEFAULT_DC_IP_LINES.joinToString("\n"), + ).orEmpty(), + logMaxMbText = ProxyConfig.formatDecimal( + preferences.getFloat( + KEY_LOG_MAX_MB, + ProxyConfig.DEFAULT_LOG_MAX_MB.toFloat(), + ).toDouble() + ), + bufferKbText = preferences.getInt( + KEY_BUFFER_KB, + ProxyConfig.DEFAULT_BUFFER_KB, + ).toString(), + poolSizeText = preferences.getInt( + KEY_POOL_SIZE, + ProxyConfig.DEFAULT_POOL_SIZE, + ).toString(), + checkUpdates = preferences.getBoolean(KEY_CHECK_UPDATES, false), + verbose = preferences.getBoolean(KEY_VERBOSE, false), + ) + } + + fun save(config: NormalizedProxyConfig) { + preferences.edit() + .putString(KEY_HOST, config.host) + .putInt(KEY_PORT, config.port) + .putString(KEY_SECRET, config.secret) + .putString(KEY_DC_IP_TEXT, config.dcIpList.joinToString("\n")) + .putFloat(KEY_LOG_MAX_MB, config.logMaxMb.toFloat()) + .putInt(KEY_BUFFER_KB, config.bufferKb) + .putInt(KEY_POOL_SIZE, config.poolSize) + .putBoolean(KEY_CHECK_UPDATES, config.checkUpdates) + .putBoolean(KEY_VERBOSE, config.verbose) + .apply() + } + + companion object { + private const val PREFS_NAME = "proxy_settings" + private const val KEY_HOST = "host" + private const val KEY_PORT = "port" + private const val KEY_SECRET = "secret" + private const val KEY_DC_IP_TEXT = "dc_ip_text" + private const val KEY_LOG_MAX_MB = "log_max_mb" + private const val KEY_BUFFER_KB = "buf_kb" + private const val KEY_POOL_SIZE = "pool_size" + private const val KEY_CHECK_UPDATES = "check_updates" + private const val KEY_VERBOSE = "verbose" + } +} diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/PythonProxyBridge.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/PythonProxyBridge.kt new file mode 100644 index 0000000..1042aa5 --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/PythonProxyBridge.kt @@ -0,0 +1,102 @@ +package org.flowseal.tgwsproxy + +import android.content.Context +import com.chaquo.python.Python +import com.chaquo.python.android.AndroidPlatform +import java.io.File +import org.json.JSONObject + +object PythonProxyBridge { + private const val MODULE_NAME = "android_proxy_bridge" + private val pythonStartLock = Any() + + fun start(context: Context, config: NormalizedProxyConfig): String { + val module = getModule(context) + return module.callAttr( + "start_proxy", + File(context.filesDir, "tg-ws-proxy").absolutePath, + config.host, + config.port, + config.secret, + config.dcIpList, + config.logMaxMb, + config.bufferKb, + config.poolSize, + config.verbose, + ).toString() + } + + fun stop(context: Context) { + if (!Python.isStarted()) { + return + } + getModule(context).callAttr("stop_proxy") + } + + fun getTrafficStats(context: Context): ProxyTrafficStats { + if (!Python.isStarted()) { + return ProxyTrafficStats() + } + + val payload = getModule(context).callAttr("get_runtime_stats_json").toString() + val json = JSONObject(payload) + return ProxyTrafficStats( + bytesUp = json.optLong("bytes_up", 0L), + bytesDown = json.optLong("bytes_down", 0L), + running = json.optBoolean("running", false), + lastError = json.optString("last_error").ifBlank { null }, + ) + } + + fun getUpdateStatus(context: Context, checkNow: Boolean = false): ProxyUpdateStatus { + val payload = getModule(context).callAttr("get_update_status_json", checkNow).toString() + val json = JSONObject(payload) + return ProxyUpdateStatus( + currentVersion = json.optString("current_version").ifBlank { "unknown" }, + latestVersion = json.optString("latest").ifBlank { null }, + hasUpdate = json.optBoolean("has_update", false), + aheadOfRelease = json.optBoolean("ahead_of_release", false), + checked = json.optBoolean("checked", false), + htmlUrl = json.optString("html_url").ifBlank { null }, + error = json.optString("error").ifBlank { null }, + ) + } + + private fun getModule(context: Context) = + getPython(context.applicationContext).getModule(MODULE_NAME) + + private fun getPython(context: Context): Python { + if (Python.isStarted()) { + return Python.getInstance() + } + synchronized(pythonStartLock) { + if (!Python.isStarted()) { + try { + Python.start(AndroidPlatform(context)) + } catch (exc: IllegalStateException) { + if (!Python.isStarted()) { + throw exc + } + } + } + } + return Python.getInstance() + } +} + +data class ProxyTrafficStats( + val bytesUp: Long = 0L, + val bytesDown: Long = 0L, + val running: Boolean = false, + val lastError: String? = null, +) + +data class ProxyUpdateStatus( + val currentVersion: String = "unknown", + val latestVersion: String? = null, + val hasUpdate: Boolean = false, + val aheadOfRelease: Boolean = false, + val checked: Boolean = false, + val htmlUrl: String? = null, + val error: String? = null, +) diff --git a/android/app/src/main/java/org/flowseal/tgwsproxy/TelegramProxyIntent.kt b/android/app/src/main/java/org/flowseal/tgwsproxy/TelegramProxyIntent.kt new file mode 100644 index 0000000..468663e --- /dev/null +++ b/android/app/src/main/java/org/flowseal/tgwsproxy/TelegramProxyIntent.kt @@ -0,0 +1,23 @@ +package org.flowseal.tgwsproxy + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri + +object TelegramProxyIntent { + fun open(context: Context, config: NormalizedProxyConfig): Boolean { + val uri = Uri.parse( + "tg://proxy?server=${Uri.encode(config.host)}&port=${config.port}&secret=dd${Uri.encode(config.secret)}" + ) + val intent = Intent(Intent.ACTION_VIEW, uri) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + return try { + context.startActivity(intent) + true + } catch (_: ActivityNotFoundException) { + false + } + } +} diff --git a/android/app/src/main/python/android_proxy_bridge.py b/android/app/src/main/python/android_proxy_bridge.py new file mode 100644 index 0000000..5a5aa85 --- /dev/null +++ b/android/app/src/main/python/android_proxy_bridge.py @@ -0,0 +1,161 @@ +import os +import threading +import time +import json +from pathlib import Path +from typing import Iterable, Optional + +from proxy.app_runtime import ProxyAppRuntime +from proxy import __version__ +import proxy.tg_ws_proxy as tg_ws_proxy + + +RELEASES_PAGE_URL = "https://github.com/Flowseal/tg-ws-proxy/releases/latest" + + +_RUNTIME_LOCK = threading.RLock() +_RUNTIME: Optional[ProxyAppRuntime] = None +_LAST_ERROR: Optional[str] = None + + +def _remember_error(message: str) -> None: + global _LAST_ERROR + _LAST_ERROR = message + + +def _normalize_dc_ip_list(dc_ip_list: Iterable[object]) -> list[str]: + if dc_ip_list is None: + return [] + + values: list[object] + try: + values = list(dc_ip_list) + except TypeError: + # Chaquopy may expose Kotlin's List as java.util.ArrayList, + # which isn't always directly iterable from Python. + if hasattr(dc_ip_list, "toArray"): + values = list(dc_ip_list.toArray()) + elif hasattr(dc_ip_list, "size") and hasattr(dc_ip_list, "get"): + size = int(dc_ip_list.size()) + values = [dc_ip_list.get(i) for i in range(size)] + else: + values = [dc_ip_list] + + return [str(item).strip() for item in values if str(item).strip()] + + +def start_proxy(app_dir: str, host: str, port: int, secret: str, + dc_ip_list: Iterable[object], log_max_mb: float = 5.0, + buf_kb: int = 256, pool_size: int = 4, + verbose: bool = False) -> str: + global _RUNTIME, _LAST_ERROR + + with _RUNTIME_LOCK: + if _RUNTIME is not None: + _RUNTIME.stop_proxy() + _RUNTIME = None + + _LAST_ERROR = None + os.environ["TG_WS_PROXY_CRYPTO_BACKEND"] = "python" + tg_ws_proxy.reset_stats() + + runtime = ProxyAppRuntime( + Path(app_dir), + logger_name="tg-ws-android", + on_error=_remember_error, + ) + runtime.reset_log_file() + runtime.setup_logging(verbose=verbose, log_max_mb=float(log_max_mb)) + + config = { + "host": host, + "port": int(port), + "secret": str(secret).strip(), + "dc_ip": _normalize_dc_ip_list(dc_ip_list), + "log_max_mb": float(log_max_mb), + "buf_kb": int(buf_kb), + "pool_size": int(pool_size), + "verbose": bool(verbose), + } + runtime.save_config(config) + + if not runtime.start_proxy(config): + _RUNTIME = None + raise RuntimeError(_LAST_ERROR or "Failed to start proxy runtime.") + + _RUNTIME = runtime + + # Give the proxy thread a short warm-up window so immediate bind failures + # surface before Kotlin reports the service as running. + for _ in range(10): + time.sleep(0.1) + with _RUNTIME_LOCK: + if _LAST_ERROR: + runtime.stop_proxy() + _RUNTIME = None + raise RuntimeError(_LAST_ERROR) + if runtime.is_proxy_running(): + return str(runtime.log_file) + + with _RUNTIME_LOCK: + runtime.stop_proxy() + _RUNTIME = None + raise RuntimeError("Proxy runtime did not become ready in time.") + + +def stop_proxy() -> None: + global _RUNTIME, _LAST_ERROR + + with _RUNTIME_LOCK: + _LAST_ERROR = None + if _RUNTIME is not None: + _RUNTIME.stop_proxy() + _RUNTIME = None + + +def is_running() -> bool: + with _RUNTIME_LOCK: + return bool(_RUNTIME and _RUNTIME.is_proxy_running()) + + +def get_last_error() -> Optional[str]: + return _LAST_ERROR + + +def get_runtime_stats_json() -> str: + with _RUNTIME_LOCK: + running = bool(_RUNTIME and _RUNTIME.is_proxy_running()) + + payload = dict(tg_ws_proxy.get_stats_snapshot()) + payload["running"] = running + payload["last_error"] = _LAST_ERROR + return json.dumps(payload) + + +def _load_update_check(): + from utils import update_check + return update_check + + +def get_update_status_json(check_now: bool = False) -> str: + payload = { + "current_version": __version__, + "latest": "", + "has_update": False, + "ahead_of_release": False, + "checked": False, + "html_url": RELEASES_PAGE_URL, + "error": "", + } + try: + update_check = _load_update_check() + if check_now: + update_check.run_check(__version__) + payload.update(update_check.get_status()) + payload["current_version"] = __version__ + payload["latest"] = payload.get("latest") or "" + payload["html_url"] = payload.get("html_url") or update_check.RELEASES_PAGE_URL + payload["error"] = payload.get("error") or "" + except Exception as exc: + payload["error"] = str(exc) + return json.dumps(payload) diff --git a/android/app/src/main/res/drawable/ic_proxy_app.xml b/android/app/src/main/res/drawable/ic_proxy_app.xml new file mode 100644 index 0000000..3608bba --- /dev/null +++ b/android/app/src/main/res/drawable/ic_proxy_app.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_proxy_notification.xml b/android/app/src/main/res/drawable/ic_proxy_notification.xml new file mode 100644 index 0000000..cd58fb9 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_proxy_notification.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/android/app/src/main/res/layout/activity_log_viewer.xml b/android/app/src/main/res/layout/activity_log_viewer.xml new file mode 100644 index 0000000..5880535 --- /dev/null +++ b/android/app/src/main/res/layout/activity_log_viewer.xml @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..aac1a85 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,424 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..4317b48 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,7 @@ + + + #1E88E5 + #0B1F33 + #F4F8FC + #FFFFFF + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..5416dee --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,75 @@ + + + TG WS Proxy + Android app for the local Telegram MTProto proxy. + Foreground service + Starting + Running + Stopped + Configure the proxy settings, then start the foreground service. + Starting embedded Python proxy for %1$s:%2$d. + Foreground service active for %1$s:%2$d. + Android background limits + Ready + Needs attention + Battery optimization: disabled for this app. + Battery optimization: still enabled, Android may stop the proxy in background. + Background restriction: not detected. + Background restriction: enabled, Android may block long-running work. + Some phones also require manual vendor settings such as Autostart, Lock in recents, or Unrestricted battery mode. + Proxy endpoint + Advanced + Actions + Updates + v%1$s + Check for updates on launch + Checking GitHub release… + Not checked yet + Automatic update checks are disabled. + Installed version %1$s matches the latest GitHub release. + Installed version %1$s is newer than the latest GitHub release. + Version %1$s is available on GitHub (installed: %2$s). + Update check failed: %1$s + Open Release Page + Proxy host + Proxy port + MTProto secret (32 hex characters) + DC to IP mappings (one DC:IP per line) + Max log size before rotation (MB) + Socket buffer size (KB) + WS pool size per DC + Verbose logging + Save Settings + Start Service + Stop Service + Restart Proxy + Open in Telegram + Open Logs + Disable Battery Optimization + Open App Settings + Last service error + Failed to open release page. + Settings saved + Foreground service start requested + Foreground service restart requested + Telegram app was not found for tg://proxy. + TG WS Proxy + Proxy service + Keeps the Telegram proxy service alive in the foreground. + MTProto %1$s:%2$d • starting embedded Python + MTProto %1$s:%2$d • proxy active + %1$s:%2$d + DC mappings: %1$d\nTraffic: ↑ %2$s/s ↓ %3$s/s\nTransferred: ↑ %4$s ↓ %5$s + Stop + Saved proxy settings are invalid. + Failed to start embedded Python proxy. + Proxy runtime stopped unexpectedly. + Proxy Logs + Shows the latest lines from the embedded Python proxy log. + Log file + Refresh Logs + Close + The log file is empty or has not been created yet. + Failed to read log file: %1$s + Showing the last part of the log file. + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..48198c7 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,11 @@ + + + + diff --git a/android/build-local-debug.sh b/android/build-local-debug.sh new file mode 100644 index 0000000..47fe6c1 --- /dev/null +++ b/android/build-local-debug.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash + +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +APP_BUILD_DIR="$ROOT_DIR/app/build" + +if [[ -z "${GRADLE_USER_HOME:-}" ]]; then + if [[ -d "$HOME/.gradle" && -w "$HOME/.gradle" ]]; then + export GRADLE_USER_HOME="$HOME/.gradle" + else + export GRADLE_USER_HOME="$ROOT_DIR/.gradle-local" + fi +fi + +mkdir -p "$GRADLE_USER_HOME" + +if [[ -d "$HOME/.local/jdk" ]]; then + export JAVA_HOME="$HOME/.local/jdk" +fi + +if [[ -d "$HOME/android-sdk" ]]; then + export ANDROID_SDK_ROOT="$HOME/android-sdk" +fi + +if [[ -n "${JAVA_HOME:-}" ]]; then + export PATH="$JAVA_HOME/bin:$PATH" +fi + +if [[ -n "${ANDROID_SDK_ROOT:-}" ]]; then + export PATH="$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools:$PATH" +fi + +if [[ -d "$HOME/.local/gradle/gradle-8.7/bin" ]]; then + export PATH="$HOME/.local/gradle/gradle-8.7/bin:$PATH" +fi + +unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy + +GRADLE_BIN="gradle" +if [[ -x "$ROOT_DIR/gradlew" ]]; then + GRADLE_BIN="$ROOT_DIR/gradlew" +fi +GRADLE_RUN_DIR="$ROOT_DIR" + +ATTEMPTS="${ATTEMPTS:-5}" +SLEEP_SECONDS="${SLEEP_SECONDS:-15}" +TASK="${1:-assembleStandardDebug}" +LOCAL_CHAQUOPY_REPO="${LOCAL_CHAQUOPY_REPO:-$ROOT_DIR/.m2-chaquopy}" +CHAQUOPY_MAVEN_BASE="${CHAQUOPY_MAVEN_BASE:-https://repo.maven.apache.org/maven2}" + +running_on_wsl_windows_mount() { + [[ -n "${WSL_DISTRO_NAME:-}" && "$ROOT_DIR" == /mnt/* ]] +} + +prepare_wsl_build_dir() { + if ! running_on_wsl_windows_mount; then + return 0 + fi + + local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/tg-ws-proxy-android-build" + local project_key + project_key="$(printf '%s' "$ROOT_DIR" | sha256sum | cut -d' ' -f1)" + local linux_build_dir="$cache_root/$project_key/app-build" + + mkdir -p "$cache_root" + mkdir -p "$linux_build_dir" + + if [[ -L "$APP_BUILD_DIR" ]]; then + return 0 + fi + + if [[ -e "$APP_BUILD_DIR" ]]; then + rm -rf "$APP_BUILD_DIR" + fi + + ln -s "$linux_build_dir" "$APP_BUILD_DIR" +} + +task_uses_legacy32() { + [[ "$TASK" =~ [Ll]egacy32 ]] +} + +task_uses_standard() { + if [[ "$TASK" =~ [Ss]tandard ]]; then + return 0 + fi + + if task_uses_legacy32; then + return 1 + fi + + return 0 +} + +prefetch_artifact() { + local relative_path="$1" + local destination="$LOCAL_CHAQUOPY_REPO/$relative_path" + + if [[ -f "$destination" ]]; then + return 0 + fi + + mkdir -p "$(dirname "$destination")" + echo "Prefetching $relative_path" + curl \ + --fail \ + --location \ + --retry 8 \ + --retry-all-errors \ + --continue-at - \ + --connect-timeout 15 \ + --speed-limit 1024 \ + --speed-time 20 \ + --max-time 90 \ + --output "$destination" \ + "$CHAQUOPY_MAVEN_BASE/$relative_path" +} + +prefetch_chaquopy_runtime() { + local artifacts=( + "com/chaquo/python/runtime/chaquopy_java/17.0.0/chaquopy_java-17.0.0.pom" + "com/chaquo/python/runtime/chaquopy_java/17.0.0/chaquopy_java-17.0.0.jar" + "com/chaquo/python/runtime/libchaquopy_java/17.0.0/libchaquopy_java-17.0.0.pom" + ) + + if task_uses_standard; then + artifacts+=( + "com/chaquo/python/runtime/libchaquopy_java/17.0.0/libchaquopy_java-17.0.0-3.12-arm64-v8a.so" + "com/chaquo/python/runtime/libchaquopy_java/17.0.0/libchaquopy_java-17.0.0-3.12-x86_64.so" + "com/chaquo/python/target/3.12.12-0/target-3.12.12-0.pom" + "com/chaquo/python/target/3.12.12-0/target-3.12.12-0-arm64-v8a.zip" + "com/chaquo/python/target/3.12.12-0/target-3.12.12-0-stdlib-pyc.zip" + "com/chaquo/python/target/3.12.12-0/target-3.12.12-0-stdlib.zip" + "com/chaquo/python/target/3.12.12-0/target-3.12.12-0-x86_64.zip" + ) + fi + + if task_uses_legacy32; then + artifacts+=( + "com/chaquo/python/runtime/libchaquopy_java/17.0.0/libchaquopy_java-17.0.0-3.11-armeabi-v7a.so" + "com/chaquo/python/target/3.11.10-0/target-3.11.10-0.pom" + "com/chaquo/python/target/3.11.10-0/target-3.11.10-0-armeabi-v7a.zip" + "com/chaquo/python/target/3.11.10-0/target-3.11.10-0-stdlib-pyc.zip" + "com/chaquo/python/target/3.11.10-0/target-3.11.10-0-stdlib.zip" + ) + fi + + for artifact in "${artifacts[@]}"; do + prefetch_artifact "$artifact" + done +} + +cleanup_stale_build_state() { + local stale_dirs=( + "$APP_BUILD_DIR/python/env" + "$APP_BUILD_DIR/intermediates/project_dex_archive" + "$APP_BUILD_DIR/intermediates/desugar_graph" + "$APP_BUILD_DIR/tmp/kotlin-classes" + "$APP_BUILD_DIR/snapshot/kotlin" + ) + + for stale_dir in "${stale_dirs[@]}"; do + if [[ -d "$stale_dir" ]]; then + rm -rf "$stale_dir" + fi + done +} + +prefetch_chaquopy_runtime +prepare_wsl_build_dir + +for attempt in $(seq 1 "$ATTEMPTS"); do + echo "==> Android build attempt $attempt/$ATTEMPTS ($TASK)" + if ( + cd "$GRADLE_RUN_DIR" + "$GRADLE_BIN" --no-daemon --console=plain "$TASK" + ); then + exit 0 + fi + + if [[ "$attempt" -lt "$ATTEMPTS" ]]; then + cleanup_stale_build_state + echo "Build failed, retrying in ${SLEEP_SECONDS}s..." + sleep "$SLEEP_SECONDS" + fi +done + +echo "Android build failed after $ATTEMPTS attempts." +exit 1 diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..bbaf05f --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("com.android.application") version "8.5.2" apply false + id("com.chaquo.python") version "17.0.0" apply false + id("org.jetbrains.kotlin.android") version "1.9.24" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..84e8962 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official +systemProp.org.gradle.internal.http.connectionTimeout=120000 +systemProp.org.gradle.internal.http.socketTimeout=120000 diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac658cd --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=120000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..050f305 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,28 @@ +pluginManagement { + repositories { + val localChaquopyRepo = file(System.getenv("LOCAL_CHAQUOPY_REPO") ?: ".m2-chaquopy") + if (localChaquopyRepo.isDirectory) { + maven(url = localChaquopyRepo.toURI()) + } + maven("https://chaquo.com/maven") + gradlePluginPortal() + google() + mavenCentral() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + val localChaquopyRepo = file(System.getenv("LOCAL_CHAQUOPY_REPO") ?: ".m2-chaquopy") + if (localChaquopyRepo.isDirectory) { + maven(url = localChaquopyRepo.toURI()) + } + maven("https://chaquo.com/maven") + google() + mavenCentral() + } +} + +rootProject.name = "tg-ws-proxy-android" +include(":app") diff --git a/proxy/app_runtime.py b/proxy/app_runtime.py new file mode 100644 index 0000000..5465b17 --- /dev/null +++ b/proxy/app_runtime.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import asyncio as _asyncio +import json +import logging +import logging.handlers +import os +import sys +import threading +import time +from pathlib import Path +from typing import Callable, Dict, Optional + +import proxy.tg_ws_proxy as tg_ws_proxy + + +DEFAULT_CONFIG = { + "port": 1443, + "host": "127.0.0.1", + "secret": os.urandom(16).hex(), + "dc_ip": ["2:149.154.167.220", "4:149.154.167.220"], + "log_max_mb": 5, + "buf_kb": 256, + "pool_size": 4, + "verbose": False, +} + + +class ProxyAppRuntime: + def __init__(self, app_dir: Path, + default_config: Optional[dict] = None, + logger_name: str = "tg-ws-runtime", + on_error: Optional[Callable[[str], None]] = None, + parse_dc_ip_list: Optional[ + Callable[[list[str]], Dict[int, str]] + ] = None, + run_proxy: Optional[Callable[..., object]] = None, + thread_factory: Optional[Callable[..., object]] = None): + self.app_dir = Path(app_dir) + self.config_file = self.app_dir / "config.json" + self.log_file = self.app_dir / "proxy.log" + self.default_config = dict(default_config or DEFAULT_CONFIG) + self.log = logging.getLogger(logger_name) + self.on_error = on_error + self.parse_dc_ip_list = parse_dc_ip_list or \ + tg_ws_proxy.parse_dc_ip_list + self.run_proxy = run_proxy or tg_ws_proxy._run + self.thread_factory = thread_factory or threading.Thread + self.config: dict = {} + self._proxy_thread = None + self._async_stop = None + + def _build_core_config(self, active_cfg: dict, dc_opt: Dict[int, str]): + port = int(active_cfg.get("port", self.default_config["port"])) + host = str(active_cfg.get("host", self.default_config["host"])) + secret = str(active_cfg.get("secret") or "").strip() + if not secret: + secret = os.urandom(16).hex() + active_cfg["secret"] = secret + + buf_kb = int(active_cfg.get("buf_kb", self.default_config["buf_kb"])) + pool_size = int(active_cfg.get( + "pool_size", self.default_config["pool_size"])) + + return tg_ws_proxy.ProxyConfig( + port=port, + host=host, + secret=secret, + dc_redirects=dc_opt, + buffer_size=max(4, buf_kb) * 1024, + pool_size=max(0, pool_size), + ) + + def ensure_dirs(self): + self.app_dir.mkdir(parents=True, exist_ok=True) + + def load_config(self) -> dict: + self.ensure_dirs() + if self.config_file.exists(): + try: + with open(self.config_file, "r", encoding="utf-8") as f: + data = json.load(f) + for key, value in self.default_config.items(): + data.setdefault(key, value) + self.config = data + return data + except Exception as exc: + self.log.warning("Failed to load config: %s", exc) + + self.config = dict(self.default_config) + return dict(self.config) + + def save_config(self, cfg: dict): + self.ensure_dirs() + self.config = dict(cfg) + with open(self.config_file, "w", encoding="utf-8") as f: + json.dump(cfg, f, indent=2, ensure_ascii=False) + + def reset_log_file(self): + if self.log_file.exists(): + try: + self.log_file.unlink() + except Exception: + pass + + def setup_logging(self, verbose: bool = False, log_max_mb: float = 5): + self.ensure_dirs() + root = logging.getLogger() + root.setLevel(logging.DEBUG if verbose else logging.INFO) + + for handler in list(root.handlers): + if getattr(handler, "_tg_ws_proxy_runtime_handler", False): + root.removeHandler(handler) + try: + handler.close() + except Exception: + pass + + fh = logging.handlers.RotatingFileHandler( + str(self.log_file), + maxBytes=max(32 * 1024, log_max_mb * 1024 * 1024), + backupCount=0, + encoding="utf-8", + ) + fh.setLevel(logging.DEBUG) + fh.setFormatter(logging.Formatter( + "%(asctime)s %(levelname)-5s %(name)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S")) + fh._tg_ws_proxy_runtime_handler = True + root.addHandler(fh) + + if not getattr(sys, "frozen", False): + ch = logging.StreamHandler(sys.stdout) + ch.setLevel(logging.DEBUG if verbose else logging.INFO) + ch.setFormatter(logging.Formatter( + "%(asctime)s %(levelname)-5s %(message)s", + datefmt="%H:%M:%S")) + ch._tg_ws_proxy_runtime_handler = True + root.addHandler(ch) + + def prepare(self) -> dict: + cfg = self.load_config() + self.save_config(cfg) + return cfg + + def _emit_error(self, text: str): + if self.on_error: + self.on_error(text) + + def _run_proxy_thread(self, port: int, dc_opt: Dict[int, str], + host: str = "127.0.0.1"): + loop = _asyncio.new_event_loop() + _asyncio.set_event_loop(loop) + stop_ev = _asyncio.Event() + self._async_stop = (loop, stop_ev) + + try: + loop.run_until_complete(self.run_proxy(stop_event=stop_ev)) + except Exception as exc: + self.log.error("Proxy thread crashed: %s", exc) + exc_text = str(exc) + if ("10048" in exc_text or + "address already in use" in exc_text.lower()): + self._emit_error( + "Не удалось запустить прокси:\n" + "Порт уже используется другим приложением.\n\n" + "Закройте приложение, использующее этот порт, " + "или измените порт в настройках прокси и перезапустите.") + else: + self._emit_error(str(exc) or exc.__class__.__name__) + finally: + loop.close() + self._async_stop = None + + def start_proxy(self, cfg: Optional[dict] = None) -> bool: + if self._proxy_thread and self._proxy_thread.is_alive(): + self.log.info("Proxy already running") + return True + + active_cfg = dict(cfg or self.config or self.default_config) + self.config = dict(active_cfg) + port = active_cfg.get("port", self.default_config["port"]) + host = active_cfg.get("host", self.default_config["host"]) + dc_ip_list = active_cfg.get("dc_ip", self.default_config["dc_ip"]) + buf_kb = active_cfg.get("buf_kb", self.default_config["buf_kb"]) + pool_size = active_cfg.get( + "pool_size", self.default_config["pool_size"]) + + try: + dc_opt = self.parse_dc_ip_list(dc_ip_list) + except ValueError as exc: + self.log.error("Bad config dc_ip: %s", exc) + self._emit_error("Ошибка конфигурации:\n%s" % exc) + return False + + tg_ws_proxy.proxy_config = self._build_core_config(active_cfg, dc_opt) + self.save_config(active_cfg) + + self.log.info("Starting proxy on %s:%d ...", host, port) + tg_ws_proxy._RECV_BUF = max(4, buf_kb) * 1024 + tg_ws_proxy._SEND_BUF = tg_ws_proxy._RECV_BUF + tg_ws_proxy._WS_POOL_SIZE = max(0, pool_size) + self._proxy_thread = self.thread_factory( + target=self._run_proxy_thread, + args=( + port, + dc_opt, + host, + ), + daemon=True, + name="proxy") + self._proxy_thread.start() + return True + + def stop_proxy(self): + if self._async_stop: + loop, stop_ev = self._async_stop + loop.call_soon_threadsafe(stop_ev.set) + if self._proxy_thread: + self._proxy_thread.join(timeout=2) + self._proxy_thread = None + self.log.info("Proxy stopped") + + def restart_proxy(self, delay_seconds: float = 0.3) -> bool: + self.log.info("Restarting proxy...") + self.stop_proxy() + time.sleep(delay_seconds) + return self.start_proxy() + + def is_proxy_running(self) -> bool: + return bool(self._proxy_thread and self._proxy_thread.is_alive()) diff --git a/proxy/crypto_backend.py b/proxy/crypto_backend.py new file mode 100644 index 0000000..7508516 --- /dev/null +++ b/proxy/crypto_backend.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +import os +from typing import Protocol + + +_SBOX = ( + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, + 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, + 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, + 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, + 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, + 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, + 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, + 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, + 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, + 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, + 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, + 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, + 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, + 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, + 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, + 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, + 0xB0, 0x54, 0xBB, 0x16, +) +_RCON = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36) + + +class AesCtrTransform(Protocol): + def update(self, data: bytes) -> bytes: + ... + + def finalize(self) -> bytes: + ... + + +def _xtime(value: int) -> int: + value <<= 1 + if value & 0x100: + value ^= 0x11B + return value & 0xFF + + +def _mul2(value: int) -> int: + return _xtime(value) + + +def _mul3(value: int) -> int: + return _xtime(value) ^ value + + +def _add_round_key(state: list[int], round_key: bytes): + for idx in range(16): + state[idx] ^= round_key[idx] + + +def _sub_bytes(state: list[int]): + for idx in range(16): + state[idx] = _SBOX[state[idx]] + + +def _shift_rows(state: list[int]): + state[1], state[5], state[9], state[13] = ( + state[5], state[9], state[13], state[1] + ) + state[2], state[6], state[10], state[14] = ( + state[10], state[14], state[2], state[6] + ) + state[3], state[7], state[11], state[15] = ( + state[15], state[3], state[7], state[11] + ) + + +def _mix_columns(state: list[int]): + for offset in range(0, 16, 4): + s0, s1, s2, s3 = state[offset:offset + 4] + state[offset + 0] = _mul2(s0) ^ _mul3(s1) ^ s2 ^ s3 + state[offset + 1] = s0 ^ _mul2(s1) ^ _mul3(s2) ^ s3 + state[offset + 2] = s0 ^ s1 ^ _mul2(s2) ^ _mul3(s3) + state[offset + 3] = _mul3(s0) ^ s1 ^ s2 ^ _mul2(s3) + + +def _rot_word(word: list[int]) -> list[int]: + return word[1:] + word[:1] + + +def _sub_word(word: list[int]) -> list[int]: + return [_SBOX[value] for value in word] + + +def _expand_round_keys(key: bytes) -> tuple[list[bytes], int]: + if len(key) not in (16, 24, 32): + raise ValueError("AES key must be 16, 24, or 32 bytes long") + + nk = len(key) // 4 + nr = {4: 10, 6: 12, 8: 14}[nk] + words = [list(key[idx:idx + 4]) for idx in range(0, len(key), 4)] + total_words = 4 * (nr + 1) + + for idx in range(nk, total_words): + temp = words[idx - 1][:] + if idx % nk == 0: + temp = _sub_word(_rot_word(temp)) + temp[0] ^= _RCON[idx // nk - 1] + elif nk > 6 and idx % nk == 4: + temp = _sub_word(temp) + words.append([ + words[idx - nk][byte_idx] ^ temp[byte_idx] + for byte_idx in range(4) + ]) + + round_keys = [] + for round_idx in range(nr + 1): + start = round_idx * 4 + round_keys.append(bytes(sum(words[start:start + 4], []))) + return round_keys, nr + + +class _PurePythonAesCtrTransform: + def __init__(self, key: bytes, iv: bytes): + if len(iv) != 16: + raise ValueError("AES-CTR IV must be 16 bytes long") + self._round_keys, self._rounds = _expand_round_keys(key) + self._counter = bytearray(iv) + self._buffer = b"" + self._buffer_offset = 0 + + def update(self, data: bytes) -> bytes: + if not data: + return b"" + + out = bytearray(len(data)) + data_offset = 0 + + while data_offset < len(data): + if self._buffer_offset >= len(self._buffer): + self._buffer = self._encrypt_block(bytes(self._counter)) + self._buffer_offset = 0 + self._increment_counter() + + available = len(self._buffer) - self._buffer_offset + chunk_size = min(len(data) - data_offset, available) + for chunk_idx in range(chunk_size): + out[data_offset + chunk_idx] = ( + data[data_offset + chunk_idx] + ^ self._buffer[self._buffer_offset + chunk_idx] + ) + data_offset += chunk_size + self._buffer_offset += chunk_size + + return bytes(out) + + def finalize(self) -> bytes: + return b"" + + def _encrypt_block(self, block: bytes) -> bytes: + state = list(block) + _add_round_key(state, self._round_keys[0]) + + for round_idx in range(1, self._rounds): + _sub_bytes(state) + _shift_rows(state) + _mix_columns(state) + _add_round_key(state, self._round_keys[round_idx]) + + _sub_bytes(state) + _shift_rows(state) + _add_round_key(state, self._round_keys[self._rounds]) + return bytes(state) + + def _increment_counter(self): + for idx in range(15, -1, -1): + self._counter[idx] = (self._counter[idx] + 1) & 0xFF + if self._counter[idx] != 0: + break + + +def _create_cryptography_transform(key: bytes, + iv: bytes) -> AesCtrTransform: + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + cipher = Cipher(algorithms.AES(key), modes.CTR(iv)) + return cipher.encryptor() + + +def create_aes_ctr_transform(key: bytes, iv: bytes, + backend: str | None = None) -> AesCtrTransform: + """ + Create a stateful AES-CTR transform. + + Windows keeps using `cryptography` by default. Android can select the + pure-Python backend to avoid native build dependencies. + """ + selected = backend or os.environ.get( + 'TG_WS_PROXY_CRYPTO_BACKEND', 'cryptography') + + if selected == 'cryptography': + return _create_cryptography_transform(key, iv) + + if selected == 'python': + return _PurePythonAesCtrTransform(key, iv) + + raise ValueError(f"Unsupported AES-CTR backend: {selected}") diff --git a/proxy/tg_ws_proxy.py b/proxy/tg_ws_proxy.py index 21ba025..e3af6e1 100644 --- a/proxy/tg_ws_proxy.py +++ b/proxy/tg_ws_proxy.py @@ -17,7 +17,7 @@ from collections import deque from dataclasses import dataclass, field from typing import Dict, List, Optional, Set, Tuple -from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from proxy.crypto_backend import create_aes_ctr_transform @dataclass @@ -332,9 +332,10 @@ def _try_handshake(handshake: bytes, secret: bytes) -> Optional[Tuple[int, bool, dec_key = hashlib.sha256(dec_prekey + secret).digest() dec_iv_int = int.from_bytes(dec_iv, 'big') - decryptor = Cipher( - algorithms.AES(dec_key), modes.CTR(dec_iv_int.to_bytes(16, 'big')) - ).encryptor() + decryptor = create_aes_ctr_transform( + dec_key, + dec_iv_int.to_bytes(16, 'big'), + ) decrypted = decryptor.update(handshake) proto_tag = decrypted[PROTO_TAG_POS:PROTO_TAG_POS + 4] @@ -367,9 +368,7 @@ def _generate_relay_init(proto_tag: bytes, dc_idx: int) -> bytes: enc_key = rnd_bytes[SKIP_LEN:SKIP_LEN + PREKEY_LEN] enc_iv = rnd_bytes[SKIP_LEN + PREKEY_LEN:SKIP_LEN + PREKEY_LEN + IV_LEN] - encryptor = Cipher( - algorithms.AES(enc_key), modes.CTR(enc_iv) - ).encryptor() + encryptor = create_aes_ctr_transform(enc_key, enc_iv) dc_bytes = struct.pack(' str: pool_total = self.pool_hits + self.pool_misses @@ -511,12 +512,34 @@ class Stats: _stats = Stats() +def reset_stats() -> None: + global _stats + _stats = Stats() + + +def get_stats_snapshot() -> Dict[str, object]: + return { + "connections_total": _stats.connections_total, + "connections_active": _stats.connections_active, + "connections_ws": _stats.connections_ws, + "connections_tcp_fallback": _stats.connections_tcp_fallback, + "connections_bad": _stats.connections_bad, + "ws_errors": _stats.ws_errors, + "bytes_up": _stats.bytes_up, + "bytes_down": _stats.bytes_down, + "pool_hits": _stats.pool_hits, + "pool_misses": _stats.pool_misses, + "last_transport_route": _stats.last_transport_route, + } + + class _WsPool: WS_POOL_MAX_AGE = 120.0 def __init__(self): self._idle: Dict[Tuple[int, bool], deque] = {} self._refilling: Set[Tuple[int, bool]] = set() + self._refill_tasks: Dict[Tuple[int, bool], asyncio.Task] = {} async def get(self, dc: int, is_media: bool, target_ip: str, domains: List[str] @@ -549,10 +572,13 @@ class _WsPool: if key in self._refilling: return self._refilling.add(key) - asyncio.create_task(self._refill(key, target_ip, domains)) + task = asyncio.create_task(self._refill(key, target_ip, domains)) + self._refill_tasks[key] = task + task.add_done_callback(lambda _t, refill_key=key: self._refill_tasks.pop(refill_key, None)) async def _refill(self, key, target_ip, domains): dc, is_media = key + tasks: List[asyncio.Task] = [] try: bucket = self._idle.setdefault(key, deque()) needed = proxy_config.pool_size - len(bucket) @@ -566,10 +592,19 @@ class _WsPool: ws = await t if ws: bucket.append((ws, time.monotonic())) + except asyncio.CancelledError: + raise except Exception: pass log.debug("WS pool refilled DC%d%s: %d ready", dc, 'm' if is_media else '', len(bucket)) + except asyncio.CancelledError: + for task in tasks: + if not task.done(): + task.cancel() + if tasks: + await asyncio.gather(*tasks, return_exceptions=True) + raise finally: self._refilling.discard(key) @@ -603,6 +638,29 @@ class _WsPool: self._schedule_refill((dc, is_media), target_ip, domains) log.info("WS pool warmup started for %d DC(s)", len(dc_redirects)) + async def close(self): + refill_tasks = list(self._refill_tasks.values()) + self._refill_tasks.clear() + for task in refill_tasks: + if not task.done(): + task.cancel() + if refill_tasks: + await asyncio.gather(*refill_tasks, return_exceptions=True) + + idle_sockets = [] + for bucket in self._idle.values(): + while bucket: + ws, _created = bucket.popleft() + idle_sockets.append(ws) + self._idle.clear() + self._refilling.clear() + + if idle_sockets: + await asyncio.gather( + *(self._quiet_close(ws) for ws in idle_sockets), + return_exceptions=True, + ) + _ws_pool = _WsPool() @@ -769,6 +827,7 @@ async def _tcp_fallback(reader, writer, dst, port, relay_init, label, return False _stats.connections_tcp_fallback += 1 + _stats.last_transport_route = "tcp_fallback" rw.write(relay_init) await rw.drain() await _bridge_tcp_reencrypt(reader, writer, rr, rw, label, @@ -838,12 +897,8 @@ async def _handle_client(reader, writer, secret: bytes): clt_enc_prekey_iv[:PREKEY_LEN] + secret).digest() clt_enc_iv = clt_enc_prekey_iv[PREKEY_LEN:] - clt_decryptor = Cipher( - algorithms.AES(clt_dec_key), modes.CTR(clt_dec_iv) - ).encryptor() - clt_encryptor = Cipher( - algorithms.AES(clt_enc_key), modes.CTR(clt_enc_iv) - ).encryptor() + clt_decryptor = create_aes_ctr_transform(clt_dec_key, clt_dec_iv) + clt_encryptor = create_aes_ctr_transform(clt_enc_key, clt_enc_iv) # fast-forward client decryptor past the 64-byte init clt_decryptor.update(ZERO_64) @@ -858,12 +913,8 @@ async def _handle_client(reader, writer, secret: bytes): relay_dec_key = relay_dec_prekey_iv[:KEY_LEN] relay_dec_iv = relay_dec_prekey_iv[KEY_LEN:] - tg_encryptor = Cipher( - algorithms.AES(relay_enc_key), modes.CTR(relay_enc_iv) - ).encryptor() - tg_decryptor = Cipher( - algorithms.AES(relay_dec_key), modes.CTR(relay_dec_iv) - ).encryptor() + tg_encryptor = create_aes_ctr_transform(relay_enc_key, relay_enc_iv) + tg_decryptor = create_aes_ctr_transform(relay_dec_key, relay_dec_iv) tg_encryptor.update(ZERO_64) @@ -965,6 +1016,7 @@ async def _handle_client(reader, writer, secret: bytes): dc_fail_until.pop(dc_key, None) _stats.connections_ws += 1 + _stats.last_transport_route = "telegram_ws_direct" splitter = None try: @@ -1087,6 +1139,7 @@ async def _run(stop_event: Optional[asyncio.Event] = None): else: await server.serve_forever() finally: + await _ws_pool.close() log_stats_task.cancel() try: await log_stats_task diff --git a/tests/test_android_proxy_bridge.py b/tests/test_android_proxy_bridge.py new file mode 100644 index 0000000..09a7b50 --- /dev/null +++ b/tests/test_android_proxy_bridge.py @@ -0,0 +1,264 @@ +import sys +import unittest +import json +import subprocess +from pathlib import Path + + +sys.path.insert(0, str( + Path(__file__).resolve().parents[1] / "android" / "app" / "src" / "main" / "python" +)) + +import android_proxy_bridge # noqa: E402 +import proxy.tg_ws_proxy as tg_ws_proxy # noqa: E402 + + +class FakeJavaArrayList: + def __init__(self, items): + self._items = list(items) + + def size(self): + return len(self._items) + + def get(self, index): + return self._items[index] + + +class AndroidProxyBridgeTests(unittest.TestCase): + def tearDown(self): + tg_ws_proxy.reset_stats() + android_proxy_bridge._LAST_ERROR = None + + def test_normalize_dc_ip_list_with_python_iterable(self): + result = android_proxy_bridge._normalize_dc_ip_list([ + "2:149.154.167.220", + " ", + "4:149.154.167.220 ", + ]) + + self.assertEqual(result, [ + "2:149.154.167.220", + "4:149.154.167.220", + ]) + + def test_get_runtime_stats_json_reports_proxy_counters(self): + tg_ws_proxy.reset_stats() + snapshot = tg_ws_proxy.get_stats_snapshot() + snapshot["bytes_up"] = 1536 + snapshot["bytes_down"] = 4096 + tg_ws_proxy._stats.bytes_up = snapshot["bytes_up"] + tg_ws_proxy._stats.bytes_down = snapshot["bytes_down"] + + result = json.loads(android_proxy_bridge.get_runtime_stats_json()) + + self.assertEqual(result["bytes_up"], 1536) + self.assertEqual(result["bytes_down"], 4096) + self.assertFalse(result["running"]) + self.assertIsNone(result["last_error"]) + + def test_get_runtime_stats_json_includes_last_error(self): + android_proxy_bridge._LAST_ERROR = "boom" + + result = json.loads(android_proxy_bridge.get_runtime_stats_json()) + + self.assertEqual(result["last_error"], "boom") + + def test_normalize_dc_ip_list_with_java_array_list_shape(self): + result = android_proxy_bridge._normalize_dc_ip_list(FakeJavaArrayList([ + "2:149.154.167.220", + "4:149.154.167.220", + ])) + + self.assertEqual(result, [ + "2:149.154.167.220", + "4:149.154.167.220", + ]) + + def test_start_proxy_saves_advanced_runtime_config(self): + captured = {} + + class FakeRuntime: + def __init__(self, *args, **kwargs): + captured["runtime_init"] = kwargs + self.log_file = Path("/tmp/proxy.log") + + def reset_log_file(self): + captured["reset_log_file"] = True + + def setup_logging(self, verbose=False, log_max_mb=5): + captured["verbose"] = verbose + captured["log_max_mb"] = log_max_mb + + def save_config(self, config): + captured["config"] = dict(config) + + def start_proxy(self, config): + captured["start_proxy"] = dict(config) + return True + + def is_proxy_running(self): + return True + + def stop_proxy(self): + captured["stop_proxy"] = True + + original_runtime = android_proxy_bridge.ProxyAppRuntime + try: + android_proxy_bridge.ProxyAppRuntime = FakeRuntime + log_path = android_proxy_bridge.start_proxy( + "/tmp/app", + "127.0.0.1", + 1443, + "0123456789abcdef0123456789abcdef", + ["2:149.154.167.220"], + 7.0, + 512, + 6, + True, + ) + finally: + android_proxy_bridge.ProxyAppRuntime = original_runtime + + self.assertEqual(log_path, "/tmp/proxy.log") + self.assertEqual(captured["config"]["secret"], "0123456789abcdef0123456789abcdef") + self.assertEqual(captured["config"]["log_max_mb"], 7.0) + self.assertEqual(captured["config"]["buf_kb"], 512) + self.assertEqual(captured["config"]["pool_size"], 6) + self.assertEqual(captured["log_max_mb"], 7.0) + self.assertTrue(captured["verbose"]) + + def test_get_update_status_json_merges_python_update_state(self): + original_load_update_check = android_proxy_bridge._load_update_check + try: + captured = {} + + class FakeUpdateCheck: + RELEASES_PAGE_URL = "https://example.com/releases/latest" + + @staticmethod + def run_check(version): + captured["run_check_version"] = version + + @staticmethod + def get_status(): + return { + "checked": True, + "latest": "1.3.1", + "has_update": True, + "ahead_of_release": False, + "html_url": "https://example.com/release", + "error": "", + } + + android_proxy_bridge._load_update_check = lambda: FakeUpdateCheck + result = json.loads(android_proxy_bridge.get_update_status_json(True)) + finally: + android_proxy_bridge._load_update_check = original_load_update_check + + self.assertEqual(captured["run_check_version"], android_proxy_bridge.__version__) + self.assertEqual(result["current_version"], android_proxy_bridge.__version__) + self.assertEqual(result["latest"], "1.3.1") + self.assertTrue(result["has_update"]) + self.assertTrue(result["checked"]) + self.assertEqual(result["html_url"], "https://example.com/release") + + def test_get_update_status_json_reports_unchecked_state(self): + original_load_update_check = android_proxy_bridge._load_update_check + try: + class FakeUpdateCheck: + RELEASES_PAGE_URL = "https://example.com/releases/latest" + + @staticmethod + def get_status(): + return { + "checked": False, + "latest": "", + "has_update": False, + "ahead_of_release": False, + "html_url": "", + "error": "", + } + + android_proxy_bridge._load_update_check = lambda: FakeUpdateCheck + result = json.loads(android_proxy_bridge.get_update_status_json(False)) + finally: + android_proxy_bridge._load_update_check = original_load_update_check + + self.assertFalse(result["checked"]) + self.assertEqual(result["current_version"], android_proxy_bridge.__version__) + + def test_get_update_status_json_reports_import_error_without_breaking_bridge(self): + original_load_update_check = android_proxy_bridge._load_update_check + try: + def fail(): + raise ModuleNotFoundError("No module named 'utils'") + + android_proxy_bridge._load_update_check = fail + result = json.loads(android_proxy_bridge.get_update_status_json(True)) + finally: + android_proxy_bridge._load_update_check = original_load_update_check + + self.assertFalse(result["checked"]) + self.assertIn("No module named 'utils'", result["error"]) + + def test_get_update_status_json_normalizes_none_fields_for_kotlin(self): + original_load_update_check = android_proxy_bridge._load_update_check + try: + class FakeUpdateCheck: + RELEASES_PAGE_URL = "https://example.com/releases/latest" + + @staticmethod + def get_status(): + return { + "checked": True, + "latest": None, + "has_update": False, + "ahead_of_release": True, + "html_url": None, + "error": None, + } + + android_proxy_bridge._load_update_check = lambda: FakeUpdateCheck + result = json.loads(android_proxy_bridge.get_update_status_json(False)) + finally: + android_proxy_bridge._load_update_check = original_load_update_check + + self.assertEqual(result["latest"], "") + self.assertEqual(result["error"], "") + self.assertEqual(result["html_url"], "https://example.com/releases/latest") + + def test_android_bridge_import_and_update_status_work_without_cryptography(self): + root = Path(__file__).resolve().parents[1] + script = f""" +import importlib.abc +import sys +from pathlib import Path + +root = Path({str(root)!r}) +sys.path.insert(0, str(root / "android" / "app" / "src" / "main" / "python")) +sys.path.insert(0, str(root)) + +class BlockCryptography(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "cryptography" or fullname.startswith("cryptography."): + raise ModuleNotFoundError("No module named 'cryptography'") + return None + +sys.meta_path.insert(0, BlockCryptography()) + +import android_proxy_bridge +print(android_proxy_bridge.get_update_status_json(False)) +""" + result = subprocess.run( + [sys.executable, "-c", script], + check=True, + capture_output=True, + text=True, + ) + payload = json.loads(result.stdout.strip()) + self.assertEqual(payload["current_version"], android_proxy_bridge.__version__) + self.assertEqual(payload["error"], "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_app_runtime.py b/tests/test_app_runtime.py new file mode 100644 index 0000000..36a4305 --- /dev/null +++ b/tests/test_app_runtime.py @@ -0,0 +1,166 @@ +import json +import tempfile +import unittest +from pathlib import Path + +from proxy.app_runtime import DEFAULT_CONFIG, ProxyAppRuntime + + +class _FakeThread: + def __init__(self, target=None, args=(), daemon=None, name=None): + self.target = target + self.args = args + self.daemon = daemon + self.name = name + self.started = False + self.join_timeout = None + self._alive = False + + def start(self): + self.started = True + self._alive = True + + def is_alive(self): + return self._alive + + def join(self, timeout=None): + self.join_timeout = timeout + self._alive = False + + +class ProxyAppRuntimeTests(unittest.TestCase): + def test_load_config_returns_defaults_when_missing(self): + with tempfile.TemporaryDirectory() as tmpdir: + runtime = ProxyAppRuntime(Path(tmpdir)) + + cfg = runtime.load_config() + + self.assertEqual(cfg, DEFAULT_CONFIG) + + def test_load_config_merges_defaults_into_saved_config(self): + with tempfile.TemporaryDirectory() as tmpdir: + app_dir = Path(tmpdir) + config_path = app_dir / "config.json" + app_dir.mkdir(parents=True, exist_ok=True) + config_path.write_text( + json.dumps({"port": 9050, "host": "127.0.0.2"}), + encoding="utf-8") + runtime = ProxyAppRuntime(app_dir) + + cfg = runtime.load_config() + + self.assertEqual(cfg["port"], 9050) + self.assertEqual(cfg["host"], "127.0.0.2") + self.assertEqual(cfg["dc_ip"], DEFAULT_CONFIG["dc_ip"]) + self.assertEqual(cfg["verbose"], DEFAULT_CONFIG["verbose"]) + + def test_invalid_config_file_falls_back_to_defaults(self): + with tempfile.TemporaryDirectory() as tmpdir: + app_dir = Path(tmpdir) + app_dir.mkdir(parents=True, exist_ok=True) + (app_dir / "config.json").write_text("{broken", encoding="utf-8") + runtime = ProxyAppRuntime(app_dir) + + cfg = runtime.load_config() + + self.assertEqual(cfg, DEFAULT_CONFIG) + + def test_start_proxy_starts_thread_with_parsed_dc_options(self): + with tempfile.TemporaryDirectory() as tmpdir: + captured = {} + thread_holder = {} + + def fake_parse(entries): + captured["dc_ip"] = list(entries) + return {2: "149.154.167.220"} + + def fake_thread_factory(**kwargs): + thread = _FakeThread(**kwargs) + thread_holder["thread"] = thread + return thread + + runtime = ProxyAppRuntime( + Path(tmpdir), + parse_dc_ip_list=fake_parse, + thread_factory=fake_thread_factory) + + started = runtime.start_proxy(dict(DEFAULT_CONFIG)) + + self.assertTrue(started) + self.assertEqual(captured["dc_ip"], DEFAULT_CONFIG["dc_ip"]) + self.assertTrue(thread_holder["thread"].started) + self.assertEqual( + thread_holder["thread"].args, + (DEFAULT_CONFIG["port"], {2: "149.154.167.220"}, + DEFAULT_CONFIG["host"])) + + def test_start_proxy_reports_bad_config(self): + with tempfile.TemporaryDirectory() as tmpdir: + errors = [] + + def fake_parse(entries): + raise ValueError("bad dc mapping") + + runtime = ProxyAppRuntime( + Path(tmpdir), + parse_dc_ip_list=fake_parse, + on_error=errors.append) + + started = runtime.start_proxy({ + "host": "127.0.0.1", + "port": 1080, + "dc_ip": ["broken"], + "verbose": False, + }) + + self.assertFalse(started) + self.assertEqual(errors, ["Ошибка конфигурации:\nbad dc mapping"]) + + def test_run_proxy_thread_reports_generic_runtime_error(self): + with tempfile.TemporaryDirectory() as tmpdir: + errors = [] + + async def fake_run_proxy(stop_event=None): + raise RuntimeError("proxy boom") + + runtime = ProxyAppRuntime( + Path(tmpdir), + on_error=errors.append, + run_proxy=fake_run_proxy, + ) + + runtime._run_proxy_thread(1443, {2: "149.154.167.220"}, "127.0.0.1") + + self.assertEqual(errors, ["proxy boom"]) + + def test_run_proxy_thread_reports_port_in_use_case_insensitively(self): + with tempfile.TemporaryDirectory() as tmpdir: + errors = [] + + async def fake_run_proxy(stop_event=None): + raise RuntimeError( + "[Errno 98] error while attempting to bind on address " + "('127.0.0.1', 1443): address already in use" + ) + + runtime = ProxyAppRuntime( + Path(tmpdir), + on_error=errors.append, + run_proxy=fake_run_proxy, + ) + + runtime._run_proxy_thread(1443, {2: "149.154.167.220"}, "127.0.0.1") + + self.assertEqual( + errors, + [ + "Не удалось запустить прокси:\n" + "Порт уже используется другим приложением.\n\n" + "Закройте приложение, использующее этот порт, " + "или измените порт в настройках прокси и перезапустите." + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_crypto_mtproto.py b/tests/test_crypto_mtproto.py new file mode 100644 index 0000000..2bd0864 --- /dev/null +++ b/tests/test_crypto_mtproto.py @@ -0,0 +1,142 @@ +import hashlib +import struct +import unittest + +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +from proxy.crypto_backend import create_aes_ctr_transform +from proxy.tg_ws_proxy import ( + PROTO_ABRIDGED_INT, + PROTO_TAG_ABRIDGED, + _MsgSplitter, + _generate_relay_init, + _try_handshake, +) + + +KEY = bytes(range(32)) +IV = bytes(range(16)) +SECRET = bytes.fromhex("0123456789abcdef0123456789abcdef") + + +def _xor(left: bytes, right: bytes) -> bytes: + return bytes(a ^ b for a, b in zip(left, right)) + + +def _keystream(size: int, key: bytes, iv: bytes) -> bytes: + transform = Cipher(algorithms.AES(key), modes.CTR(iv)).encryptor() + return transform.update(b"\x00" * size) + + +def _build_client_handshake( + dc_raw: int, + proto_tag: bytes = PROTO_TAG_ABRIDGED, + secret: bytes = SECRET, +) -> bytes: + packet = bytearray(64) + packet[8:40] = KEY + packet[40:56] = IV + + dec_key = hashlib.sha256(KEY + secret).digest() + plain_tail = proto_tag + struct.pack(" bytes: + transform = Cipher( + algorithms.AES(relay_init[8:40]), + modes.CTR(relay_init[40:56]), + ).encryptor() + transform.update(b"\x00" * 64) + return transform.update(plaintext) + + +class CryptoBackendTests(unittest.TestCase): + def test_python_backend_matches_cryptography_stream(self): + cryptography_transform = create_aes_ctr_transform( + KEY, IV, backend="cryptography") + python_transform = create_aes_ctr_transform(KEY, IV, backend="python") + + chunks = [ + b"", + b"\x00" * 16, + bytes(range(31)), + b"telegram-proxy", + b"\xff" * 64, + ] + + cryptography_out = b"".join( + cryptography_transform.update(chunk) for chunk in chunks + ) + cryptography_transform.finalize() + python_out = b"".join( + python_transform.update(chunk) for chunk in chunks + ) + python_transform.finalize() + + self.assertEqual(python_out, cryptography_out) + + def test_unknown_backend_raises_error(self): + with self.assertRaises(ValueError): + create_aes_ctr_transform(KEY, IV, backend="missing") + + +class MtProtoHandshakeTests(unittest.TestCase): + def test_try_handshake_reads_non_media_dc(self): + handshake = _build_client_handshake(dc_raw=2) + + result = _try_handshake(handshake, SECRET) + + self.assertEqual(result[:3], (2, False, PROTO_TAG_ABRIDGED)) + + def test_try_handshake_reads_media_dc(self): + handshake = _build_client_handshake(dc_raw=-4) + + result = _try_handshake(handshake, SECRET) + + self.assertEqual(result[:3], (4, True, PROTO_TAG_ABRIDGED)) + + def test_try_handshake_rejects_wrong_secret(self): + handshake = _build_client_handshake(dc_raw=2) + + result = _try_handshake( + handshake, + bytes.fromhex("fedcba9876543210fedcba9876543210"), + ) + + self.assertIsNone(result) + + def test_generate_relay_init_encodes_proto_and_signed_dc(self): + relay_init = _generate_relay_init(PROTO_TAG_ABRIDGED, -3) + decryptor = Cipher( + algorithms.AES(relay_init[8:40]), + modes.CTR(relay_init[40:56]), + ).encryptor() + + decrypted = decryptor.update(relay_init) + + self.assertEqual(decrypted[56:60], PROTO_TAG_ABRIDGED) + self.assertEqual(struct.unpack(" bytes: + return bytes(a ^ b for a, b in zip(left, right)) + + +def _build_client_handshake(dc_raw: int, proto_tag: bytes) -> bytes: + packet = bytearray(64) + packet[8:40] = KEY + packet[40:56] = IV + + dec_key = hashlib.sha256(KEY + SECRET).digest() + decryptor = Cipher(algorithms.AES(dec_key), modes.CTR(IV)).encryptor() + keystream = decryptor.update(b"\x00" * 64) + + plain_tail = proto_tag + struct.pack("